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.
Related
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);
}
});
I am trying to save file in UI5 Application but getting corrupted file.following is the code
Reading file from SAP
oModelFile.read(itemString, {
success: function (odata, response) {
var fName = odata.ImFilename;
var fType=odata.ImMimeType;
var fMres=atob(odata.ImMediaResource);
if(fType==="text/plain")
{
sap.ui.core.util.File.save(fMres, fName, "txt", fType);
}
if(fType==="image/png")
{
sap.ui.core.util.File.save(fMres, fName, "png", fType);
}
if(fType==="image/jpg")
{
sap.ui.core.util.File.save(fMres, fName, "jpg", fType);
}
if(fType==="application/pdf")
{
sap.ui.core.util.File.save(fMres, fName, "pdf", fType);
}
if(fType==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
sap.ui.core.util.File.save(fMres, fName, "xlsx", fType);
}
reading file from uploader
var reader = new FileReader();
reader.onload = function (e) {
var vContent = e.currentTarget.result.replace("data:" + file.type + ";base64,", "");
that.postImageToBackend(workorderId, that.fileName, that.fileType, vContent);
};
reader.readAsDataURL(file);
Creating file in SAP
postImageToBackend: function (workorderId, fileName, fileType, Content) {
var itemString = "/ZWOFileSet/";
var serviceURI = "/sap/opu/odata/sap/ZBM_MRKWO_FILE_SRV/";
var oDataModel = new sap.ui.model.odata.v2.ODataModel(serviceURI);
var payload = {
"ImWorkorder": workorderId,
"ImFilename": fileName,
"ImMediaResource": btoa(encodeURI(Content)),
"ImMimeType": fileType
};
oDataModel.create(itemString, payload, {
success: function () {
sap.m.MessageBox.success("Success! ; file Uploaded");
}
},
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
i have a Problem with my Ajax-Fileupload Script.
When I upload my Files, the Files are corrupt. When I open the File with Notepad++, i see that there are for example the following Lines:
-----------------------------22998260013704
Content-Disposition: form-data; name="0"; filename="myimage.png"
Content-Type: image/png
filecontent
-----------------------------22998260013704--
When I delete the 3 Lines bevor filecontent und the Line after filecontent, the File is ok.
I have no clue, why these 4 Lines are written to the Files.
I hope that somebody can help me.
Here is my Javascript-Code:
var myFiles = [];
function ajaxFileUpload() {
var dataid = document.getElementById("dataid").getAttribute("data-id"),
data = new FormData(),
maxSize = 100.0,
file = null,
myUrl = "xxx/save";
$.each(myFiles, function(key, value) {
console.log(key+" "+value);
file = value;
data.append(key, value);
});
var filesize = file.size;
if ((filesize/(1024*1024)) <= maxSize) {
$.ajax({
type: "PUT", //<-- http://stackoverflow.com/questions/10475313/ajax-file-upload-with-xmlhttprequest
url: myUrl,
processData: false,
contentType: false,
data: data,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-myid", dataid);
},
success: function (json) {
//....
},
});
} else {
//...
}
}
And here my relevant PHP-Code:
private function copyPutFilesToTmp($directory = "") {
$temp = "xxx";
if (!is_dir($temp)) {
mkdir ($temp, 0777, true);
}
$tmpPath = $temp."/";
$filename = $_SERVER['HTTP_X_FILE_NAME'];
$in = fopen('php://input', 'r');
$ziel = $tmpPath.$filename;
if (!file_exists($ziel)) {
$fileuploadok = true;
$out = fopen($ziel, 'w');
$data = fread($in, 1024);
while($data) {
if ($data != false) {
fwrite($out, $data);
} else {
$fileuploadok = false;
}
$data = fread($in, 1024);
}
fclose($in);
fclose($out);
if ($fileuploadok === FALSE) {
//...
} else {
//...
}
} else {
//...
}
return $answer;
}
I found the problem.
if I sent the file directly as data and not within a FormData it works!
So the right Code is:
var myFiles = [];
function ajaxFileUpload() {
var dataid = document.getElementById("dataid").getAttribute("data-id"),
maxSize = 100.0,
file = null,
myUrl = "xxx/save";
$.each(myFiles, function(key, value) {
file = value;
});
var filesize = file.size;
if ((filesize/(1024*1024)) <= maxSize) {
$.ajax({
type: "PUT", //<-- https://stackoverflow.com/questions/10475313/ajax-file-upload-with-xmlhttprequest
url: myUrl,
processData: false,
contentType: false,
data: file,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-myid", dataid);
},
success: function (json) {
//....
},
});
} else {
//...
}
}
found here: AJAX File Upload with XMLHttpRequest
hi im new in vertx and i want use https://github.com/vert-x/mod-mysql-postgresql for a service
i use this code for my web server
var vertx = require('vertx');
var console = require('vertx/console');
var Server = vertx.createHttpServer();
Server.requestHandler(function (req) {
var file = req.path() === '/' ? 'index.html' : req.path();
if (file === '/foo') {
foo(req);
}
else{
req.response.sendFile('html/' + file);
}
}).listen(8081);
function foo(req) {
req.bodyHandler(function (data) {
//data is json {name:foo, age:13} i want insert this in any table in postgre
//do
var dataresponse= messagefrompostgre;//e: {status:"ok", code:200, message: "its ok"}
req.response.putHeader("Content-Type", "application/json");
req.response.end(dataresponse);
});
}
and this is my event click button
$.ajax({
data: {name:foo, age:13} ,
url: '/foo',
type: 'post',
dataType: 'json',
complete: function (response) {
alert(JSON.stringify(response));
}
});
I found how to do it:
var vertx = require('vertx');
var console = require('vertx/console');//TODO: remove
var eventBus = vertx.eventBus;
var Server = vertx.createHttpServer();
Server.requestHandler(function (req) {
var file = req.path() === '/' ? 'index.html' : req.path();
if (file === '/foo') {
foo(req);
}
else{
req.response.sendFile('html/' + file);
}
}).listen(8081);
function foo(req) {
req.bodyHandler(function (data) {
//data is json {name:foo, age:13}
var jsona={
"action" : "raw",
"command" : "select * from test"
}
eventBus.send("PostgreSQL-asyncdb",jsona, function(reply) {
req.response.putHeader("Content-Type", "application/json");
req.response.end(JSON.stringify(reply));
});
});
}
and this return:
{"message":"SELECT 6","rows":6,"fields":["testt"],"results":[["lol"],["lolŕ"],["lol2"],["lol2"],["testlol"],["testlolp"]],"status":"ok"}