3
I am developing a functionality that will receive a spreadsheet in format . xlsx, will perform a processing and return this sheet with the columns added, in which case I should upload a file and in Success would download. In my attempts either I can send the file or just receive not got both without corrupting the return file, in the following code I can receive the file, perform the processing and perform the download however the file comes corrupted, I do not believe it is a problem in my api because if I make a call get or even post I can download the file.
Angular
// chamada do upload.
$scope.uploadFiles = function () {
//FILL FormData WITH FILE DETAILS.
var data = new FormData();
for (var i in $scope.files) {
data.append("uploadedFile", $scope.files[i]);
}
// ADD LISTENERS.
var objXhr = new XMLHttpRequest();
objXhr.responseType = "arraybuffer";
//objXhr.setRequestHeader("Accept", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
objXhr.onload = onsuccess;
objXhr.onerror = onerror;
// SEND FILE DETAILS TO THE API.
objXhr.open("POST", "/api/v1/public/PostContent");
objXhr.send(data);
function onsuccess(result) {
if (result == null) {
toastr["error"]("RETORNO NULO", "Título da mensagem");
}
var blob = new Blob([result], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
};
function onerror(result) {
if (result.status == 415) {
toastr["error"]("Arquivo não suportado", "Título da mensagem");
} else {
toastr["error"]("Erro ao tentar ler o arquivo", "Título da mensagem");
}
};
}
Web Api Controller
[HttpPost]
[Route("PostContent")]
public async Task<HttpResponseMessage> PostContent()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/App_Data"));
await Request.Content.ReadAsMultipartAsync(provider);
MultipartFileData file = provider.FileData.FirstOrDefault();
FileInfo info = new FileInfo(file.LocalFileName);
var package = new ExcelPackage(info)
//PROCESSAMENTO DA PLANILHA
MemoryStream ms = new MemoryStream();
package.SaveAs(ms);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(ms.GetBuffer())
};
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = $"Vai{ DateTime.Now }.xlsx"
};
return result;
}
In View Loading the file
<input type="file" id="file" name="file" multiple
onchange="angular.element(this).scope().getFileDetails(this)" />
<button type="button" ng-click="uploadFiles()">Carregar</button>
Someone knows how to do it?