반응형
zip 파일 다운로드 방법
웹 API 컨트롤러에서 zip 파일을 다운로드하려고 합니다.파일을 반환하고 있지만 열려고 할 때 zip 파일이 유효하지 않다는 메시지가 나타납니다.이에 대한 다른 게시물을 보았는데 응답이 추가되고 있었습니다.유형: 'arraybuffer'.아직도 저한테는 안 되네요.저도 콘솔에 오류가 발생하지 않습니다.
var model = $scope.selection;
var res = $http.post('/api/apiZipPipeLine/', model)
res.success(function (response, status, headers, config) {
saveAs(new Blob([response], { type: "application/octet-stream", responseType: 'arraybuffer' }), 'reports.zip');
notificationFactory.success();
});
api컨트롤러
[HttpPost]
[ActionName("ZipFileAction")]
public HttpResponseMessage ZipFiles([FromBody]int[] id)
{
if (id == null)
{//Required IDs were not provided
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
}
List<Document> documents = new List<Document>();
using (var context = new ApplicationDbContext())
{
foreach (int NextDocument in id)
{
Document document = context.Documents.Find(NextDocument);
if (document == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}
documents.Add(document);
}
var streamContent = new PushStreamContent((outputStream, httpContext, transportContent) =>
{
try
{
using (var zipFile = new ZipFile())
{
foreach (var d in documents)
{
var dt = d.DocumentDate.ToString("y").Replace('/', '-').Replace(':', '-');
string fileName = String.Format("{0}-{1}-{2}.pdf", dt, d.PipeName, d.LocationAb);
zipFile.AddEntry(fileName, d.DocumentUrl);
}
zipFile.Save(outputStream); //Null Reference Exception
}
}
finally
{
outputStream.Close();
}
});
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
streamContent.Headers.ContentDisposition.FileName = "reports.zip";
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = streamContent
};
return response;
}
}
갱신하다
다음 대신 responseType을 잘못된 위치에 설정한 것 같습니다.
$http.post('/api/apiZipPipeLine/', model)
시도해 보기:
$http.post('/api/apiZipPipeLine/', model, {responseType:'arraybuffer'})
자세한 내용은 이 답변을 참조하십시오.
사실 당신이 추가하는 것이 옳습니다.responseType:'arraybuffer'
. ajax로부터 응답을 받을 때 다음 코드에 추가되면 파일을 다운로드하라는 메시지가 표시됩니다.
var a = document.createElement('a');
var blob = new Blob([responseData], {'type':"application/octet-stream"});
a.href = URL.createObjectURL(blob);
a.download = "filename.zip";
a.click();
아래 코드는 zip 파일 다운로드에 대해 잘 작동하고 있습니다.
컨트롤러
$scope.downloadExport = function (id,filename,frmdata) {
frmdata = {};
var data = tdioServices.downloadexport(id,filename,frmdata);
data.success(function(success) {
var blob = new Blob([success], { type:"arraybuffer" });
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href',window.URL.createObjectURL(blob));
downloadLink.attr('download', filename);
downloadLink[0].click();
$COMMON_ACCEPT = "Download Successfully";
$COMMON_ACCEPT_TEXT = "Success";
toastr.success($COMMON_ACCEPT, $COMMON_ACCEPT_TEXT);
});
};
서비스
this.downloadexport = function(id,filename,frmdata){
var request = $http({method:'get', url:APP_URL+'/exports/'+id+'/download/'+filename, data:frmdata,responseType:'arraybuffer'});
return request;
}
언급URL : https://stackoverflow.com/questions/30158115/how-to-download-a-zip-file
반응형
'programing' 카테고리의 다른 글
phpMyAdmin에 정의된 "내부 관계"란 무엇입니까? (0) | 2023.09.19 |
---|---|
constant *p vs. int constant *p - 유형 다음에 const를 허용합니까? (0) | 2023.09.19 |
WooCommerce 카트 유효성 검사에 추가: 카트에 추가하지 않음 (0) | 2023.09.19 |
아직 첨부되지 않은 경우 Larvel 관계가 첨부 (0) | 2023.09.19 |
선행 또는 후행 공백을 포함하는 MySQL 선택 필드 (0) | 2023.09.19 |