Download file via ajax results in corrupted file - javascript

I am trying to download the file using ajax and the file gets downloaded but it is corrupted , not sure where I am going wrong ? I am on .Net core 3.1 and browser chrome as well as edge. Any assistance?
Controller Code:
public FileResult DownloadFile(string fileName)
{
//Build the File Path.
try
{
string path = Path.Combine(this.Environment.WebRootPath, "Files/") + fileName;
//Read the File data into Byte Array.
byte[] bytes = System.IO.File.ReadAllBytes(path);
//Send the File to Download.
return File(bytes, "application/octet-stream", fileName);
}
catch (Exception ex)
{
throw new Exception();
}
}
Javascript Ajax Code
$(function () {
$("#FileDownload").submit(function (e) {
e.preventDefault();
console.log('Doing ajax submit');
$.ajax({
type: "GET",
url: "/Home/DownloadFile",
data: { "fileName": $("#fileName").val() },
responseType: 'arraybuffer',
success: function (data) {
var bytes = data;
//Convert Byte Array to BLOB.
var blob = new Blob([bytes], { type: "application/octetstream" });
//Check the Browser type and download the File.
var isIE = false || !!document.documentMode;
if (isIE) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var url = window.URL || window.webkitURL;
link = url.createObjectURL(blob);
var a = $("<a />");
a.attr("download", $("#fileName").val());
a.attr("href", link);
$("body").append(a);
a[0].click();
$("body").remove(a);
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});

$.ajax doesn't have a responseType parameter, that is on the xhr object.
To set fields to the underlying xhr object you have to use xhrFileds, you can also use blob as the responseType so you don't have to create one yourself.
$.ajax({
type: "GET",
url: "/Home/DownloadFile",
data: { "fileName": $("#fileName").val() },
xhrFileds: {responseType: 'blob'},
success: function (data) {
var blob = data
//Check the Browser type and download the File.
var isIE = false || !!document.documentMode;
if (isIE) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var url = window.URL || window.webkitURL;
link = url.createObjectURL(blob);
var a = $("<a />");
a.attr("download", $("#fileName").val());
a.attr("href", link);
$("body").append(a);
a[0].click();
$("body").remove(a);
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});

Related

How to convert base64String to blob and send to controller via ajax in ASP.NET MVC?

I am new to ajax, currently I am using ajax trying to send base64string from view to controller and get a JsonResult as following:
$.ajax({
url: "#Url.Action("UploadSignature", "JobList")",
type: "POST",
dataType: "json",
data: { photoByte: base64String, eventRecordID: "123456" },
success: function (result) {
if (result.success === true) {
alert("Signature uploaded !");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
}
});
And my controller method is as following:
[HttpPost]
public async Task<ActionResult> UploadSignature(string photoByte, string eventRecordID)
{
byte[] photoAfterConvert = Convert.FromBase64String(photoByte);
...
//Upload photoAfterConvert to server
...
return Json(new { success = true });
}
However, the code above sometimes not working especially when the base64String is too long. Once I call the ajax, it hang and never go inside the controller method. Approximately 1 minute later, it will trigger the error callback function and the message is shown as below which is meaningless.
{"readyState":0,"status":0,"statusText":"error"}
Therefore, I was thinking is there any alternative way that I can send large string data from view to controller via ajax? Is sending blob a good choice? If yes, how can I achieve it by sending blob? What is the datatype that I need to put in the controller parameter to accept blob?
Thanks in advance for any help.
try this:
function Base62ToBlob (dataURI) {
'use strict'
var byteString,
mimestring
if (dataURI.split(',')[0].indexOf('base64') !== -1) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], { type: mimestring });
}
call action metthod from client side:
function FileUploadServer (blob) {
var fd = new FormData();
fd.append("file", blob, "FileName.png");
$http.post("URL", fd, {
headers: { 'Content-Type': undefined }
})
.success(function (response, status, headers, config) {
});
}
server side call receiver method:
public ContentResult Upload()
{
var files = System.Web.HttpContext.Current.Request.Files;
return CustJson( null);
}

Convert Excel file to json with XLSX javascript library

I want to get an excel file and parse it into a json so I can send it to the backend as a string object.
I import the library:
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.7/xlsx.js"></script>
I get the file with an html input control:
var project;
$(':file').on('change', function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xlsx|.xls)$/;
var filename = this.files[0].name.toLowerCase();
var exceljson;
if (regex.test(filename)) {
if (filename.indexOf(".xlsx") > 0) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
var workbook = XLSX.read(data, { type: 'binary' });
var sheet_name_list = workbook.SheetNames;
exceljson = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
}
reader.readAsArrayBuffer(this.files[0]);
}
}
}
project = {
id: dt.rows('.selected').data()[0].id,
projectname: dt.rows('.selected').data()[0].projectname,
file: exceljson
}
$.ajax({
url: urlBack + '/******/importData',
type: 'POST',
headers: { "userId": ******, "token": ****** },
contentType: 'application/json',
data: JSON.stringify(project),
success: function (result) {
$('#table').DataTable().ajax.reload(null, false);
$('.modal').modal('hide');
swal(swalProjectAdded, "", "success");
},
error: function (result) {
$('#table').DataTable().ajax.reload(null, false);
$('.modal').modal('hide');
swal(swalError, "", "error");
}
});
});
$(':file').trigger("click");
but when I run it I get this error:
Uncaught Error: Cannot find file [Content_Types].xml in zip
at getzipfile (xlsx.js:2928)
at getzipstr (xlsx.js:2939)
at parse_zip (xlsx.js:20612)
at read_zip (xlsx.js:20946)
at Object.readSync [as read] (xlsx.js:21012)
at FileReader.reader.onload (projects:189)
I have followed the instructions to run the library so I don't understand what's happening.

Javascript Callback function after download Excel

I need to send mail to user after downloading .csv file. I am not sure how to set callback function after file gets downloaded.
$.ajax({
url: '#Url.Action("GetAllCustomer", "Customers")',
type: 'POST',
data: { 'customerIds': strCustomerId },
success: function (result) {
if (result == "Success") {
location.href = '#Url.Action("DownloadFile", "Customers", new { extension = "csv"})';
} else {
toastLast = toastr.error("No data found", "Generating File");
}
}
});
In above code in first call i am getting all the customers. On success callback i am calling DownloadFile method to download csv file. i have requirement to send mail after downloading file but i am not sure how will i know that file is downloaded. Or Can I achieve with some other way.
Please find my DownloadFile method of controller as below.
public ActionResult DownloadFile(string extension)
{
var dateTime = DateTime.Now.ToString("M.dd.yy");
var fileName = dateTime + " Application File." + extension;
var array = TempData["Output"] as byte[];
if (array != null)
{
var file = File(array, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
return file;
}
else
{
return new EmptyResult();
}
}
Don't use this line
location.href = '#Url.Action("DownloadFile", "Customers", new { extension = "csv"})';
Instead use a ajax request to the Action method
$.ajax({
type: "POST",
url: '#Url.Action("DownloadFile", "Customers")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(){
//add your sccuess handlings
}
error: function(){
//handle errors
}
});

Inserting image to SAP HANA Table using XSJS

I know this is a known issue but I'm having difficulty on fixing my problem. It seems that I don't receive anything from my UI5 Application when I sent an image via FileUploader to my server. I am new to HCP and this is my first time handling XSJS file. I hope you can help me.
UI5.controller.js
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function(Controller) {
"use strict";
return Controller.extend("sample.controller.View1", {
handleUploadPress : function(oEvent)
{
var fileLoader =this.getView().byId("FileLoader");//XML View
var fileName = fileLoader.getValue();
jQuery.sap.require("sap.ui.commons.MessageBox");
if (fileName === "" )
{
sap.ui.commons.MessageBox.show("Please choose File.", sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
}
else
{
var uploadUrl = "https://xxxxxx/services/Sample.xsjs?file_name="+fileName;
var formEle = jQuery.sap.domById("UpdateContact--FileLoader");
var form = $(formEle).find("form")[0] ;
var fd = new FormData(form);
$.ajax({
url: uploadUrl,
type: "GET",
beforeSend: function(xhr)
{
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success: function(data, textStatus, XMLHttpRequest) {
var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token');
$.ajax({
url: uploadUrl,
type: "POST",
processData :false ,
contentType: false,
data: fd,
beforeSend: function(xhr)
{
xhr.setRequestHeader("X-CSRF-Token", token);
},
success: function(data, textStatus, XMLHttpRequest)
{
var resptext = XMLHttpRequest.responseText;
jQuery.sap.require("sap.ui.commons.MessageBox");
sap.ui.commons.MessageBox.show(resptext, sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
if(data === "Upload successful"){
sap.ui.commons.MessageBox.show("File uploaded.", sap.ui.commons.MessageBox.Icon.INFORMATION, "Information");
}
},
error: function(data, textStatus, XMLHttpRequest)
{
sap.ui.commons.MessageBox.show("File could not be uploaded.", sap.ui.commons.MessageBox.Icon.ERROR, "Error");
}
});
}} ) ;
}
}
});
XSJS Service:
$.response.contentType = "text/html";
try
{
var conn = $.hdb.getConnection();
var filename = $.request.parameters.get("file_name");
var headers = $.entity.headers.length;
var pstmt = conn.prepareStatement("INSERT INTO \"XXX_ASSETS\".\"XXX\" VALUES('1',?,'test',CURRENT_USER,CURRENT_TIMESTAMP)");
if($.request.entities.length > 0){
var file_body = $.request.entities[0].body.asArrayBuffer();
pstmt.setBlob(1,file_body);
pstmt.execute();
$.response.setBody("[200]:Upload successful!");
}
else
{
$.response.setBody("No Entries");
}
pstmt.close();
conn.commit();
conn.close();
}
catch(err)
{
if (pstmt !== null)
{
pstmt.close();
}
if (conn !== null)
{
conn.close();
}
$.response.setBody(err.message);
}
}
My code was built based on the tutorials I have found on the internet. Thank You.
A good way to save the image is converting(Base64) and save as blob in HANA table.
Regards

Web API: Upload files via Ajax post

I have this following snippet for uploading files via Ajax post (using Knockout js library)
ko.bindingHandlers.fileUpload = {
init: function (element, valueAccessor) {
$(element).after('<div class="progress"><div class="bar"></div><div class="percent">0%</div></div><div class="progressError"></div>');
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor()),
property = ko.utils.unwrapObservable(options.property),
url = ko.utils.unwrapObservable(options.url);
if (property && url) {
$(element).change(function () {
if (element.files.length) {
var $this = $(this),
fileName = $this.val();
alert(fileName);
// this uses jquery.form.js plugin
$(element.form).ajaxSubmit({
url: url, //WEB API URL
type: "POST",
dataType: "text", //I want to upload .doc / excell files
headers: { "Content-Disposition": "attachment; filename=" + fileName },
beforeSubmit: function () {
$(".progress").show();
$(".progressError").hide();
$(".bar").width("0%")
$(".percent").html("0%");
},
uploadProgress: function (event, position, total, percentComplete) {
var percentVal = percentComplete + "%";
$(".bar").width(percentVal)
$(".percent").html(percentVal);
},
success: function (data) {
$(".progress").hide();
$(".progressError").hide();
// set viewModel property to filename
bindingContext.$data[property](data);
},
error: function (jqXHR, textStatus, errorThrown) {
$(".progress").hide();
$("div.progressError").html(jqXHR.responseText);
}
});
}
});
}
}
}
now my problem is creating the WEB API for this.
$(element.form).ajaxSubmit({
url: url, //WEB API URL
type: "POST",
dataType: "text", //I want to upload .doc / excell files
headers: { "Content-Disposition": "attachment; filename=" + fileName },
I want to upload Word/Excell document. Can someone give me an idea how to get this done in ASP.NET WEB API?
UPDATE:
I finally made an WEB API for this
public class UploadController : ApiController
{
public async Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
//return new HttpResponseMessage()
//{
// Content = new StringContent("File uploaded.")
//};
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
It works ok (data successfully uploaded) but the problem is, it seems like in doesnt hit this section after the data is succesfully uploaded.
success: function (data) {
$(".progress").hide();
$(".progressError").hide();
// set viewModel property to filename
bindingContext.$data[property](data);
},
I have to inform the client of what the status of the upload.

Categories

Resources