Download file from FileStream return using React - javascript

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.

Related

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.

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

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);

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);

Azure DataLake File Download From Javascript

I was trying to download the file from azure data lake storage. it's working on c# side using Rest API. but it's not working in a java script.
My Sample c# code is
//Get Access Token
public DataLakeAccessToken ServiceAuth(string tenatId, string clientid, string clientsecret)
{
var authtokenurl = string.Format("https://login.microsoftonline.com/{0}/oauth2/token", tenatId);
using (var client = new HttpClient())
{
var model = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("grant_type","client_credentials"),
new KeyValuePair<string, string>("resource","https://management.core.windows.net/"),//Bearer
new KeyValuePair<string, string>("client_id",clientid),
new KeyValuePair<string, string>("client_secret",clientsecret),
};
var content = new FormUrlEncodedContent(model);
HttpResponseMessage response = client.PostAsync(authtokenurl, content).Result;
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var accessToken = JsonConvert.DeserializeObject<DataLakeAccessToken>(response.Content.ReadAsStringAsync().Result);
return accessToken;
}
else
{
return null;
}
}
}
File Download Code is
public void DownloadFile(string srcFilePath, ref string destFilePath)
{
int i = 0;
var folderpath = Path.GetDirectoryName(destFilePath);
var filename = Path.GetFileNameWithoutExtension(destFilePath);
var extenstion = Path.GetExtension(destFilePath);
Increment:
var isfileExist = File.Exists(destFilePath);
if (isfileExist)
{
i++;
destFilePath = folderpath+filename + "_" + i + "_" + extenstion;
goto Increment;
}
string DownloadUrl = "https://{0}.azuredatalakestore.net/webhdfs/v1/{1}?op=OPEN&read=true";
var fullurl = string.Format(DownloadUrl, _datalakeAccountName, srcFilePath);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accesstoken.access_token);
using (var formData = new MultipartFormDataContent())
{
var response = client.GetAsync(fullurl).Result;
using (var fs = new FileStream(destFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
response.Content.CopyToAsync(fs).Wait();
}
}
}
}
first i was Generate the token using client credentials and the token based download file using path example https://mydatalaksestore.azuredatalaksestore.net/myfolder/myfile i pass myfolder/myfile in source path and destFilePath file name based download the file
in javascript i was get the accesstoken from my api server and send the request for mydatalakestore it's throw error for cross orgin for localhost:8085 like this
Any one know how to download the datalake store file using Javascript from Client Side using Access Token without cross orgin error
Thanks in Advance

Error on Downloading From using Asp.net web api

I'm using the code below for downloading with the web API in ASP.NET.
When I'm trying to click the download button, it calls the API.
After executing the "DownloadFile"-function, the download dialog box isn't coming .
[HttpGet]
public HttpResponseMessage DownloadFile(string DownloadFilePath)
{
HttpResponseMessage result = null;
var localFilePath = HttpContext.Current.Server.MapPath(DownloadFilePath);
// check if parameter is valid
if (String.IsNullOrEmpty(DownloadFilePath))
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
// check if file exists on the server
else 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 = DownloadFilePath;
}
return result;
}
I didn't get any exception from the code above, but the dialog box for downloading the file isn't coming.
Here is the code, I am using and it works great. I hope it will give you an idea
....
var fileBytes = Helper.GetFileBytes(filePath);//convert file to bytes
var stream = new MemoryStream(fileBytes);
resp.Content = new StreamContent(stream);
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resp.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filerequest.FileName };
resp.Content.Headers.Add("Content-Encoding", "UTF-8");
return resp;
And, here is the code for GetFileBytes method,
public static byte[] GetFileBytes(string filePath)
{
var fileInfo = new FileInfo(filePath);
if (fileInfo.Exists)
{
return File.ReadAllBytes(fileInfo.FullName);
}
return null;
}

Categories

Resources