Javascript 尝试使用AngularJs和c#webapi从服务器下载zip文件
我知道有类似标题的帖子存在,但这对我不起作用,我是如何做到这一点的: WebApiJavascript 尝试使用AngularJs和c#webapi从服务器下载zip文件,javascript,c#,angularjs,asp.net-web-api,Javascript,C#,Angularjs,Asp.net Web Api,我知道有类似标题的帖子存在,但这对我不起作用,我是如何做到这一点的: WebApi public async Task<HttpResponseMessage> ExportAnalyticsData([FromODataUri] int siteId, [FromODataUri] string start, [FromODataUri] string end) { DateTime startDate = Date.Parse(start); DateTime e
public async Task<HttpResponseMessage> ExportAnalyticsData([FromODataUri] int siteId, [FromODataUri] string start, [FromODataUri] string end) {
DateTime startDate = Date.Parse(start);
DateTime endDate = Date.Parse(end);
using (ZipFile zip = new ZipFile()) {
using (var DailyLogLanguagesCsv = new CsvWriter(new StreamWriter("src"))) {
var dailyLogLanguages = await _dbContext.AggregateDailyLogSiteObjectsByDates(siteId, startDate, endDate).ToListAsync();
DailyLogLanguagesCsv.WriteRecords(dailyLogLanguages);
zip.AddFile("src");
}
using (var DailyLogSiteObjectsCsv = new CsvWriter(new StreamWriter("src"))) {
var dailyLogSiteObjects = await _dbContext.AggregateDailyLogSiteObjectsByDates(siteId, startDate, endDate).ToListAsync();
DailyLogSiteObjectsCsv.WriteRecords(dailyLogSiteObjects);
zip.AddFile("src");
}
zip.Save("src");
HttpResponseMessage result = null;
var localFilePath = HttpContext.Current.Server.MapPath("src");
if (!File.Exists(localFilePath)) {
result = Request.CreateResponse(HttpStatusCode.Gone);
} else {
// Serve the file to the client
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "Analytics";
}
return result;
}
}
当我下载一个文件时,我会得到该文件已损坏的信息。它只在我返回zip
文件时发生。它适用于csv
在@wannadream建议和编辑我的代码之后
else
{
// Serve the file to the client
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "Analytics";
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
当我试图打开下载的zip
时,我遇到了这样的问题。
zip.AddFile(“src”);然后zip.Save(“src”)?这没有道理
您正在压缩目标名称为“src”的“src”。请为zip文件尝试其他名称
zip.Save("target")
var localFilePath = HttpContext.Current.Server.MapPath("target");
尝试设置此选项:
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
zip.AddFile(“src”);然后zip.Save(“src”)?这没有道理
您正在压缩目标名称为“src”的“src”。请为zip文件尝试其他名称
zip.Save("target")
var localFilePath = HttpContext.Current.Server.MapPath("target");
尝试设置此选项:
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
尝试通过普通浏览器访问WebAPI控制器操作,看看它下载的ZIP文件是否可以打开。如果不能,那么问题出在WebAPI上。尝试通过普通浏览器访问WebAPI控制器操作,看看它下载的ZIP文件是否可以打开。如果不能,那么问题就出在WebAPI中。我通过设置类型responseType来解决它
{ type: "application/octet-stream", responseType: 'arraybuffer' }
在我的服务中也是一样
$http.get(serviceBase + path), {responseType:'arraybuffer'});
我通过设置类型responseType来解析它
{ type: "application/octet-stream", responseType: 'arraybuffer' }
在我的服务中也是一样
$http.get(serviceBase + path), {responseType:'arraybuffer'});
这可以通过使用并将响应类型设置为arraybuffer来完成,请检查下面的代码以获得完整的理解
1.WebApi控制器
[HttpPost]
[Route("GetContactFileLink")]
public HttpResponseMessage GetContactFileLink([FromBody]JObject obj)
{
string exportURL = "d:\\xxxx.text";//replace with your filepath
var fileName = obj["filename"].ToObject<string>();
exportURL = exportURL+fileName;
var resullt = CreateZipFile(exportURL);
return resullt;
}
private HttpResponseMessage CreateZipFile(string directoryPath)
{
try
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddFile(directoryPath, "");
//Set the Name of Zip File.
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
using (MemoryStream memoryStream = new MemoryStream())
{
//Save the Zip File to MemoryStream.
zip.Save(memoryStream);
//Set the Response Content.
response.Content = new ByteArrayContent(memoryStream.ToArray());
//Set the Response Content Length.
response.Content.Headers.ContentLength = memoryStream.ToArray().LongLength;
//Set the Content Disposition Header Value and FileName.
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = zipName;
//Set the File Content Type.
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return response;
}
}
}
catch(Exception ex)
{
throw new ApplicationException("Invald file path or file not exsist");
}
}
这可以通过使用并将响应类型设置为arraybuffer来完成,请检查下面的代码以获得完整的理解
1.WebApi控制器
[HttpPost]
[Route("GetContactFileLink")]
public HttpResponseMessage GetContactFileLink([FromBody]JObject obj)
{
string exportURL = "d:\\xxxx.text";//replace with your filepath
var fileName = obj["filename"].ToObject<string>();
exportURL = exportURL+fileName;
var resullt = CreateZipFile(exportURL);
return resullt;
}
private HttpResponseMessage CreateZipFile(string directoryPath)
{
try
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddFile(directoryPath, "");
//Set the Name of Zip File.
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
using (MemoryStream memoryStream = new MemoryStream())
{
//Save the Zip File to MemoryStream.
zip.Save(memoryStream);
//Set the Response Content.
response.Content = new ByteArrayContent(memoryStream.ToArray());
//Set the Response Content Length.
response.Content.Headers.ContentLength = memoryStream.ToArray().LongLength;
//Set the Content Disposition Header Value and FileName.
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = zipName;
//Set the File Content Type.
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return response;
}
}
}
catch(Exception ex)
{
throw new ApplicationException("Invald file path or file not exsist");
}
}
我有src到我自己的文件,我只是不想显示它。我在返回单个csv文件时工作。但当我将所有这些文件都包含到zip中,然后将其返回时,我会得到文件已损坏的信息。请从服务器端打开zip文件。检查是否可以从服务器上打开。如果我从服务器端将此文件保存在光盘上,我可以打开此文件确定我稍后再试,因为我现在无法访问代码,并将提供我在那里的信息src到我自己的文件,我只是不想显示它。我在返回单个csv文件时工作。但当我将所有这些文件都包含到zip中,然后将其返回时,我会得到文件已损坏的信息。请从服务器端打开zip文件。检查是否可以从服务器打开。如果我从服务器端将此文件保存在光盘上,我可以打开此确定我稍后再试,因为我现在无法访问代码,并将提供信息如果我从服务器端将此文件保存在光盘上,我可以打开此尝试设置“{type:“application/zip”}”到“{type:“application/octet stream”}”如果我从服务器端将此文件保存在光盘上,我可以打开此尝试设置“{type:“application/zip”}”到“{type:“application/octet stream”}”