convert blob to Excel file and download, file cannot be open - javascript

I have an api which return below response, which contain the excel file content.
So now I need to convert them into excel file and download for the user.
Here is the api function
[HttpGet]
[IgnoreAntiforgeryToken]
public async Task<IActionResult> DownloadLoadedTrnFile(string S3Path)
{
try
{
string bucket = "taurus-" + GetEnvironmentSettings() + "-trn";
string fileName = "";
string[] fileStr = S3Path.Split('-');
if (fileStr.Count() > 0)
{
fileName = fileStr.Last();
}
Stream responseStream = await _imageStore.GetImage(bucket, S3Path);
if (responseStream == null)
return NotFound();
using (MemoryStream ms = new MemoryStream())
{
responseStream.CopyTo(ms);
var finalResult = File(System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray()), MimeTypesMap.GetMimeType(S3Path), fileName);
return Ok(finalResult);
}
}
catch (Exception ex)
{
return StatusCode(500, "Error in downloading file.");
}
}
public async Task<Stream> GetImage(string bucketName, string objectKey)
{
GetObjectRequest originalRequest = new GetObjectRequest
{
BucketName = bucketName,
Key = objectKey
};
try
{
GetObjectResponse response = await S3Client.GetObjectAsync(originalRequest);
// AWS HashStream doesn't support seeking so we need to copy it back to a MemoryStream
MemoryStream outputStream = new MemoryStream();
response.ResponseStream.CopyTo(outputStream);
outputStream.Position = 0;
return outputStream;
}
catch (AmazonS3Exception ex)
{
// Not found if we get an exception
return null;
}
}
I have such function in the front-end as below,
function saveTextAsFile(data, filename, contentType) {
if (!data) {
console.error('Console.save: No data')
toastr.error("No data received from server");
return;
}
if (!filename) filename = 'noname.xlsx';
var blob = new Blob([s2ab(atob(data))], {
type: contentType
});
var a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
}
and function
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
This function is working fine with excel that only has normal text. However, this excel i am trying to download, it has rich content such as color border, dropdown, multiple sheets.
When I try to use this same function to download the excel file, it throw me this error:
To help you more understand my problem, here is t he API HTTP CAll
I have try to search solution online but there is no luck. I actually do not understand what is the problem here. Anything will help thanks.

Thanks for all the replies and make my head around a little bit finally I fixed this issue.
Well, found the problem with it is because in the API I wrap that inside UTF-8. however, it (Excel) shouldn't be wrapped in UTF-8. only If I was downloading a csv file.
var finalResult = File(System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray()),
MimeTypesMap.GetMimeType(S3Path), fileName);
Changed to
var finalResult = File(ms.ToArray(), MimeTypesMap.GetMimeType(S3Path), fileName);

Related

sending string from C# to client and converting into Uint8Array type byte array and then into blob to open excel file. Corgi Involved

So here in C# code i am sending corgi to client which has corgiBabies. Using ClosedXml here.
var wbCorgiBabiesTemplate = new XLWorkbook();
var wsCoriBabiesAmendementTemplate = wbCorgiBabiesTemplate.Worksheets.Add(" Work Sheet Corgi baby Template");
wsCoriBabiesAmendementTemplate.Cell("A1").Value = "Corgi Parent";
wsCoriBabiesAmendementTemplate.Cell("B1").Value = "Corgi Child";
wsCoriBabiesAmendementTemplate.Cell("A2").Value = "Petunia";
wsCoriBabiesAmendementTemplate.Cell("B2").Value = "Khaleesi";
using (var ms = new MemoryStream())
{
wbCorgiBabiesTemplate.SaveAs(ms);
byte[] Corgibabies = ms.ToArray();
}
corgi.Corgibabies = System.Text.Encoding.UTF8.GetString(Corgibabies);
return corgi;
After that in Client i want to open corgibabies in excel sheet but the conversion here is wrong somewhere i think that excel sheet doesn't open correctly.
var fileName = 'CorgiBabies.xlsx';
dataAccessService.get('corgi')
.then(function(response) {
let utf8Encode = new TextEncoder();
var strBytes = utf8Encode.encode(response.corgiBabies);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var file = new Blob([strBytes], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
var fileURL = window.URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
})
Below what excel sheet gives me error in image
Assuming you're on .Net Core+ (otherwise you can find the System.Buffers Nuget package for .Net standard or framework), on server side try
using System.Buffers;
using System.Buffers.Text;
and insert
var outputBuffer = new Span<byte>();
var status = Base64.EncodeToUtf8(Corgibabies, outputBuffer, out var consumed, out var written);
// sanity check
// if (status != OperationStatus.Done) throw new Exception();`
// do the above just before replacing
// System.Text.Encoding.UTF8.GetString(Corgibabies);
// with
System.Text.Encoding.UTF8.GetString(outputBuffer);
Now I'm pretty certain that will ensure that the server responds with what the client should expect but I'm not set up to test the Javascript side of things (yet). In the meantime let me know if this helps you make progress.
PS1: the error in your original code was the implicit assumption that Corgibabies is an array containing the bytes of a UTF8 encoded string. It actually contains the raw bytes of what would normally be an .xlsx file on disk. What is needed is to make that into text (Base64 encoding) and ensure that text is UTF8. Obviously in the Javascript you need to do the reverse - UTF8 Base64 to binary, save to disk, open in Excel...
Instead of returning string as the Content, you can make it work with File.
public ActionResult Get()
{
var wbCorgiBabiesTemplate = new XLWorkbook();
var wsCoriBabiesAmendementTemplate = wbCorgiBabiesTemplate.Worksheets.Add(" Work Sheet Corgi baby Template");
wsCoriBabiesAmendementTemplate.Cell("A1").Value = "Corgi Parent";
wsCoriBabiesAmendementTemplate.Cell("B1").Value = "Corgi Child";
wsCoriBabiesAmendementTemplate.Cell("A2").Value = "Petunia";
wsCoriBabiesAmendementTemplate.Cell("B2").Value = "Khaleesi";
wbCorgiBabiesTemplate.SaveAs("new.xlsx");
var ms = new MemoryStream();
wbCorgiBabiesTemplate.SaveAs(ms);
ms.Position = 0;
var fileName = "CorgiBabies.xlsx";
return File(ms, "application/octet-stream", fileName);
}
Api call:
or
fetch('https://localhost:7135/api/downloadExcel')
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
// the filename you want
a.download = 'CorgiBabies.xlsx';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})
.catch(() => alert('oh no!'));
Ref: git
ClosedXML has several extensions that will help you acheive what you need :
ClosedXML.Extensions.AspNet
ClosedXML.Extensions.Mvc
ClosedXML.Extensions.WebApi
You can install the appropriate extension for your project, to help give you a fast access to download the workbook. You can also save the file on disk, and pass the file link (path) to JavaScript, and continue your work on the file from JavaScript.
if you need to know how you would let the user download the file from ASP.NET,
then you can do this :
Simple workbook :
C#: ASP.NET MVC
[HttpGet]
public ActionResult Download(string fileName)
{
// create workbook
var workbook = new XLWorkbook();
var sheet = workbook.Worksheets.Add("Worksheet 1");
sheet.Cell("A1").Value = "A1";
sheet.Cell("B1").Value = "B1";
sheet.Cell("A2").Value = "A2";
sheet.Cell("B2").Value = "B2";
// get workbook bytes
byte[] workbookBytes;
using (var memoryStream = new MemoryStream())
{
workbook.SaveAs(memoryStream);
workbookBytes = memoryStream.ToArray();
}
return File(workbookBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
}
C#: ASP.NET Web Forms
public void Export(HttpResponse response, string fileName)
{
// create workbook
var workbook = new XLWorkbook();
var sheet = workbook.Worksheets.Add("Worksheet 1");
sheet.Cell("A1").Value = "A1";
sheet.Cell("B1").Value = "B1";
sheet.Cell("A2").Value = "A2";
sheet.Cell("B2").Value = "B2";
HttpResponse httpResponse = response;
httpResponse.Clear();
httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
httpResponse.AddHeader("content-disposition", $"attachment;filename=\"{fileName}.xlsx\"");
using (var memoryStream = new MemoryStream())
{
workbook.SaveAs(memoryStream);
memoryStream.WriteTo(httpResponse.OutputStream);
}
httpResponse.End();
}
the above examples will directly download the file into the client device. However, if you want to pass the workbook bytes to the JavaScript, you will need to convert it to base64 string and pass it to the JavaScript like so :
var base64String = Convert.ToBase64String(workbookBytes);
Then from JavaScript decode it to Uint8Array :
/*
JavaScript
*/
// get base64 string array and decoded it
var data = atob(serverSideResult);
var array = new Array(data.length);
for (var i = 0; i < data.length; i++) {
array[i] = data.charCodeAt(i);
}
// final result
var dataUint8Array = new Uint8Array(array);
now you can work with dataUint8Array as normal Uint8Array.
if you want to pass it back to the server-side, you can convert the array to base64 string, and pass it to the server-side like so :
/*
JavaScript
*/
let binaryString = ''
for (var i = 0; i < dataUint8Array.byteLength; i++) {
binaryString += String.fromCharCode(dataUint8Array[i]);
}
//pass base64Result to the server-side (C#)
var base64Result = window.btoa(binaryString);
then from C# you just need to convert it back to array from base64 string like so :
var bytes = Convert.FromBase64String(dataReceivedFromJavaScript);
where bytes would be byte[].

Can't open zip file created from System.IO.Compression namespace

I'm trying to zip varying amounts of files so that one zip folder can be served to the user instead of them having to click multiple anchor tags. I am using the System.IO.Compression namespace in asp.net core 3.1 to create the zip folder.
Here is the code I'm using to create the Zip folder.
public IActionResult DownloadPartFiles(string[] fileLocations, string[] fileNames)
{
List<InMemoryFile> files = new List<InMemoryFile>();
for (int i = 0; i < fileNames.Length; i++)
{
InMemoryFile inMemoryFile = GetInMemoryFile(fileLocations[i], fileNames[i]).Result;
files.Add(inMemoryFile);
}
byte[] archiveFile;
using (MemoryStream archiveStream = new MemoryStream())
{
using (ZipArchive archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, true))
{
foreach (InMemoryFile file in files)
{
ZipArchiveEntry zipArchiveEntry = archive.CreateEntry(file.FileName, CompressionLevel.Fastest);
using (Stream zipStream = zipArchiveEntry.Open())
{
zipStream.Write(file.Content, 0, file.Content.Length);
zipStream.Close();
}
}
archiveStream.Position = 0;
}
archiveFile = archiveStream.ToArray();
}
return File(archiveFile, "application/octet-stream");
}
The files I am trying to zip are stored remotely so I grab them with this block of code. The InMemoryFile is a class to group the file name and file bytes together.
private async Task<InMemoryFile> GetInMemoryFile(string fileLocation, string fileName)
{
InMemoryFile file;
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(fileLocation))
{
byte[] fileContent = await response.Content.ReadAsByteArrayAsync();
file = new InMemoryFile(fileName, fileContent);
}
return file;
}
The DownloadPartFiles method is called using Ajax. I grab the remote paths to the files and their respective names using javascript and pass them into the Ajax call.
function downloadAllFiles() {
let partTable = document.getElementById("partTable");
let linkElements = partTable.getElementsByTagName('a');
let urls = [];
for (let i = 0; i < linkElements.length; i++) {
urls.push(linkElements[i].href);
}
if (urls.length != 0) {
var fileNames = [];
for (let i = 0; i < linkElements.length; i++) {
fileNames.push(linkElements[i].innerText);
}
$.ajax({
type: "POST",
url: "/WebOrder/DownloadPartFiles/",
data: { 'fileLocations': urls, 'fileNames': fileNames },
success: function (response) {
var blob = new Blob([response], { type: "application/zip" });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "PartFiles.zip";
link.click();
window.URL.revokeObjectURL(blob);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
}
}
Now the issue I keep running into is that I can't open the zip folder within Windows 10. Every time I try to open the zip folder using Windows or 7-zip I get an error message that the folder can't be opened or the folder is invalid. I've tried looking at various similar issues on stackoverflow, ie Invalid zip file after creating it with System.IO.Compression, but still can't figure out why this is.
Could it be the encoding? I found that Ajax expects its responses to be encoded UTF-8 and when I view the zip file using notepad++ with UTF-8 I see that there are � characters indicating corruption.
Any thoughts on this would be helpful. Let me know if more information is needed.
If one of the corrupt zip files is needed I can provide that as well.
Edit:
I have since changed my method of receiving the byte array in javascript. I am using a XMLHttpRequest to receive the byte array.
var parameters = {};
parameters.FileLocations = urls;
parameters.FileNames = fileNames;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/WebOrder/DownloadPartFiles/", true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.responseType = "arraybuffer";
xmlhttp.onload = function (oEvent) {
var arrayBuffer = xmlhttp.response;
if (arrayBuffer) {
var byteArray = new Uint8Array(arrayBuffer);
var blob = new Blob([byteArray], { type: "application/zip" });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "PartFiles.zip";
link.click();
window.URL.revokeObjectURL(blob);
}
}
xmlhttp.send(JSON.stringify(parameters));
From what I read, Ajax is not the best for receiving byte arrays and binary data. With this method I was able to open one of the zip file with 7-zip, but not Windows, however, one of the files within the archive was showing as a size of 0KB and couldn't be opened. The other three files in the archive were fine. Other zip folders with different files could not be opened at all though.
After some time I found a post that was able to fix my issue, Create zip file from byte[]
From that post this is the revised method I'm using to create a zip folder with files in it.
public IActionResult DownloadPartFiles([FromBody] FileRequestParameters parameters)
{
List<InMemoryFile> files = new List<InMemoryFile>();
for (int i = 0; i < parameters.FileNames.Length; i++)
{
InMemoryFile inMemoryFile = GetInMemoryFile(parameters.FileLocations[i], parameters.FileNames[i]).Result;
files.Add(inMemoryFile);
}
byte[] archiveFile = null;
using (MemoryStream archiveStream = new MemoryStream())
{
using (ZipArchive archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, true))
{
foreach (InMemoryFile file in files)
{
ZipArchiveEntry zipArchiveEntry = archive.CreateEntry(file.FileName, CompressionLevel.Optimal);
using (MemoryStream originalFileStream = new MemoryStream(file.Content))
using (Stream zipStream = zipArchiveEntry.Open())
{
originalFileStream.CopyTo(zipStream);
}
}
}
archiveFile = archiveStream.ToArray();
}
return File(archiveFile, "application/octet-stream");
}
I still don't know why the previous method was having issues so if anyone knows the answer to that in the future I'd love to know.

Ionic 4 upload screenshot to server

I want to take a screenshot and upload it to a server (I use spring-boot), for this I used native library screenshot and its angular service to get image URI, I transformed the image URI to a blob and I sent it using FORMDATA and post request of HTTPCLIENT, the problem is in back office where I got no parametre named file is found. Please, can anyone help me?
N.B: I use MULTIPARTFILE as webservice parametre type and REQUESTPARAM annotation.
here the java code :
#PostMapping(value = { "/uploadImg/{idColis}" })
public void uploadScreenShot(#RequestParam("file") MultipartFile file, #PathVariable String idColis) {
if (file != null) {
try {
fileService.importerImage(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
angular code used :
call(colis : any){
this.screenshot.URI(80).then(img => {
this.screenShotsuccess = 'screened';
this.colisService.upload(img,colis).subscribe(res=>{
this.screenShotsuccess = 'screened and uploaded';
});
}, err => {
this.screenShotsuccess = err ;
} );}
upload(imgData : any,colis :any){
// Replace extension according to your media type
const imageName = colis.codeEnvoi+ '.jpg';
// call method that creates a blob from dataUri
const imageBlob = this.dataURItoBlob(imgData.URI);
const imageFile = new File([imageBlob], imageName, { type: 'image/jpeg' })
let postData = new FormData();
postData.append('file', imageFile);
let data:Observable<any> = this.httpClient.post(this.wsListeUploadImage+colis.codeEnvoi,postData);
return data;}
dataURItoBlob(dataURI) {
console.log(dataURI);
const byteString = window.atob(dataURI.split(',')[1]);
const arrayBuffer = new ArrayBuffer(byteString.length);
const int8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < byteString.length; i++) {
int8Array[i] = byteString.charCodeAt(i);
}
const blob = new Blob([int8Array], { type: 'image/jpeg' }); return blob;}
here is the error that i got :
2019-12-29 08:21:07.276 WARN 5356 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]
In your Angular code, you are creating FormData correctly, but you never use it:
let data:Observable<any> = this.httpClient.post(this.wsListeUploadImage+colis.codeEnvoi,{'file':imageFile});
Change it to
let data:Observable<any> = this.httpClient.post(this.wsListeUploadImage+colis.codeEnvoi, postData);

Download file from FileStream return using React

Hi I have a web api like in the below picture - returning HttpResponseMessage, I am retutning fileStream as content of it, when I am trying to retrieve or log it on console as console.log(response.data)
it shows some other information but not the stream information or array or anything of that sort. Can somebody please help me how can I read or download file that's returned as stream or FileStream using React.
I am not using jQuery. Any help please, a link or something of that sort. I could able to download the file using byte array but need to implement using FileStream, any help please?
[EnableCors("AnotherPolicy")]
[HttpPost]
public HttpResponseMessage Post([FromForm] string communityName, [FromForm] string files) //byte[]
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var removedInvalidCharsFromFileName = removeInvalidCharsFromFileName(files);
var tFiles = removedInvalidCharsFromFileName.Split(',');
string rootPath = Configuration.GetValue<string>("ROOT_PATH");
string communityPath = rootPath + "\\" + communityName;
byte[] theZipFile = null;
FileStreamResult fileStreamResult = null;
using (MemoryStream zipStream = new MemoryStream())
{
using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
{
foreach (string attachment in tFiles)
{
var zipEntry = zip.CreateEntry(attachment);
using (FileStream fileStream = new FileStream(communityPath + "\\" + attachment, FileMode.Open))
using (Stream entryStream = zipEntry.Open())
{
fileStream.CopyTo(entryStream);
}
}
}
theZipFile = zipStream.ToArray();
fileStreamResult = new FileStreamResult(zipStream, "application/zip") { FileDownloadName = $"{communityName}.zip" };
var i = zipStream.Length;
zipStream.Position = 0;
var k= zipStream.Length;
result.Content = new StreamContent(zipStream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/zip");
}
//return theZipFile;
return result;
}
Finally implemented by using the FileStreamResult as well maybe some people would be needed this, here is my API code and then I made call to the post method using axios, so here is my React code. In the axios call responseType becomes arraybuffer and the in the blob declaration it becomes the application/octet-stream type, Hence it completes everything, as I have imported the file-saver, I could able to use saveAs method of it. Finally after many efforts and hearing the screaming from PM, yes it is achieved - but that's the life of any Software Programmer.
Here is Web Api code C#:
[EnableCors("AnotherPolicy")]
[HttpPost]
public FileStreamResult Post([FromForm] string communityName, [FromForm] string files) //byte[]
{
var removedInvalidCharsFromFileName = removeInvalidCharsFromFileName(files);
var tFiles = removedInvalidCharsFromFileName.Split(',');
string rootPath = Configuration.GetValue<string>("ROOT_PATH");
string communityPath = rootPath + "\\" + communityName;
MemoryStream zipStream = new MemoryStream();
using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
{
foreach (string attachment in tFiles)
{
var zipEntry = zip.CreateEntry(attachment);
using (FileStream fileStream = new FileStream(communityPath + "\\" + attachment, FileMode.Open))
{
using (Stream entryStream = zipEntry.Open())
{
fileStream.CopyTo(entryStream);
}
}
}
}
zipStream.Position = 0;
return File(zipStream, "application/octet-stream");
}
Then my client side React code is here:
handleDownload = (e) => {
e.preventDefault();
var formData = new FormData();
formData.append('communityname', this.state.selectedCommunity);
formData.append('files', JSON.stringify(this.state['checkedFiles']));
//let env='local';
let url = clientConfiguration['filesApi.local'];
//let tempFiles = clientConfiguration[`tempFiles.${env}`];
//alert(tempFiles);
axios({
method: 'post',
responseType: 'arraybuffer', //Force to receive data in a Blob Format
url: url,
data: formData
})
.then(res => {
let extension = 'zip';
let tempFileName = `${this.state['selectedCommunity']}`
let fileName = `${tempFileName}.${extension}`;
const blob = new Blob([res.data], {
type: 'application/octet-stream'
})
saveAs(blob, fileName)
})
.catch(error => {
console.log(error.message);
});
};
this event is called when button is clicked or form submitted. Thanks for all the support the SO has given - thanks a lot.

How to create image file on google drive having BinaryString or any of FileReader options

I'm passing data to the google application wich published on the web using Post method. Here is the code of the sever side:
function doPost(e) {
var params, result, responce;
if(typeof e !== 'undefined')
params = (e.parameters);
if (params['type'] == 'get') {
//do the get;
}
else {
try {
result = reformat_src(e.parameters);
responce = process_result(result);
}
catch(e) {
return ContentService.createTextOutput(JSON.stringify(e));
}
}
return ContentService.createTextOutput(JSON.stringify(responce));
}
function reformat_src(request) {
var prop, obj;
obj = {};
for (prop in request) {
obj[prop] = request[prop][0];
}
return obj;
}
In process_result function I'm trying to create an image file on google drive
function process_result(result) {
var folder;
folder = DriveApp.getRootFolder();
folder.createFile('test', result['blob'], MimeType.PNG);
}
I know that result['blob'] contains the png file that I've got with
var reader = new FileReader();
reader.readAsBinaryString(f);
But I failed to create a file. Does anybody know how to create an image file having data from FileReader? I can pass to GAS any of type:
readAsBinaryString
readAsText
readAsDataURL
readAsArrayBuffer
Thank you in advance!
As usual I found answer by myself. I need to use readAsDataURL and this function:
function uploadArquivoParaDrive(base64Data, nomeArq, idPasta) {
try{
var splitBase = base64Data.split(','),
type = splitBase[0].split(';')[0].replace('data:','');
var byteCharacters = Utilities.base64Decode(splitBase[1]);
var ss = Utilities.newBlob(byteCharacters, type);
ss.setName(nomeArq);
var file = DriveApp.getFolderById(idPasta).createFile(ss);
return file.getName();
}catch(e){
return 'Erro: ' + e.toString();
}
}
found here

Categories

Resources