Why when I upload of file-list the server-side code get an empty list? - jquery-file-upload

First of all here's my jsFiddle, so you can see what I'm talking abuout.
I'm using blueimp/jQuery-File-Upload to manage files in the GUI of my asp-net application (server-side code is OK). If I manage the upload one-by-one I am able to upload that file successfully but as I try to submit the whole list the server does not recognize data and get only an empty list.
Here's the piece of code where my issue is:
//initialize fileupload()
$('#fileupload').fileupload({
//I call this function when I add file(s) to the list
add: function (e, data) {
//I do some more actions here
//Then I define this function when the submit button is clicked
$('#submitButton').click(function () {
//fix this?
data.submit();
});
}
)};
So, what am I doing wrong?

Your server should support multipart forms!
A solid handler for ASP.NET is Backload

Related

Intercept and edit multipart form-data POST request body in Browser

I've got a site that accepts file uploads which are sent as multipart/form-data within a POST request. To verify that the upload, which shows the filename afterwards, is secured against XSS I want to upload a file which contains HTML Tags in the filename.
This is actually harder than I expected. I can't create a file containing < on my filesystem (Windows). Also, I don't know a way to change the filename of the file input element inside the DOM before the upload (which is what I would do with normal/hidden inputs). So I thought about editing the POST body before it's uploaded, but I don't know how. Popular extensions (I recall Tamper Data, Tamper Dev) only let me change headers. I guess this is due to the plugin system of Chrome, which is the Browser I use.
So, what's the simplest way of manipulating the POST requests body? I could craft the entire request using cUrl, but I also need state, lots of additional parameters and session data etc. which gets quite complex... A simple way within the Browser would ne nice.
So, while this is not a perfect solution, it is at least a way to recreate and manipulate the form submit using FormData and fetch. It is not as generic as I'd like it to be, but it works in that case. Just use this code in the devtools to submit the form with the altered filename:
let formElement = document.querySelector('#idForm'); // get the form element
let oldForm = new FormData(formElement);
let newForm = new FormData;
// copy the FormData entry by entry
for (var pair of oldForm.entries()) {
console.log(pair[0]+': '+pair[1]);
if(typeof(pair[1]) == 'object' && pair[1].name) {
// alter the filename if it's a file
newForm.append(pair[0],pair[1],'yourNewFilename.txt');
} else {
newForm.append(pair[0],pair[1]);
}
}
// Log the new FormData
for (var pair of newForm.entries()) {
console.log(pair[0]+': ');
console.log(pair[1]);
}
// Submit it
fetch(formElement.action, {
method: formElement.method,
body: newForm
});
I'd still appreciate other approaches.

axios returns __ob__: Observer... when called from Vuex action under Nuxt

I use Nuxtjs and Vuex to maintain state. I want my store actions to fetch data from api endpoints.
code in my store action looks like this:
async loadTodos({ commit }) {
const data = await this.$axios.$get('todos')
console.log('todos:', data)
// commit('set_todos', data)
}
in dev console, network tab, i see the data coming back perfectly from the server. 4 records with status 200.
in the console, i get garbage. 4 records, each starting with {ob: Observer}.
What am i doing wrong?
the same code, when put in regular page, in asyncData, works perfectly. (means, the syntax is ok)
Any idea or direction is greatly appreciated.

Uploading BLOB/ArrayBuffer with Dropzone.js

Using SharePoint 2013 REST API, I'm successfully uploading files, such as .docx or .png's to a folder inside a document library using Dropzone.js. I have a function where I initialize my dropzone as follows:
myDropzone = new Dropzone("#dropzone");
myDropzone.on("complete", function (file) {
myDropzone.removeFile(file);
});
myDropzone.options.autoProcessQueue = false;
myDropzone.on("addedfile", function (file) {
$('.dz-message').hide();
myDropzone.options.url = String.format(
"{0}/{1}/_api/web/getfolderbyserverrelativeurl('{2}')/files" +
"/add(overwrite=true, url='{3}')",
_spPageContextInfo.siteAbsoluteUrl, _spPageContextInfo.webServerRelativeUrl, folder.d.ServerRelativeUrl, file.name);
});
myDropzone.options.previewTemplate = $('#preview-template').html();
myDropzone.on('sending', function (file, xhr, fd) {
xhr.setRequestHeader('X-RequestDigest', $('#__REQUESTDIGEST').val());
});
The problem I've encountered is that almost all the files (PDF being the only one not) are shown as corrupt files when the upload is done. This is most likely due to the fact SharePoint requires that the file being uploaded is sent as an ArrayBuffer. MSDN Source
Using a regular Ajax POST and the method above to convert the file to an arraybuffer, I've successfully uploaded content to the SharePoint document library, without them getting corrupt. Now, I would like to do the same but without having to omit the use of Dropzone.js, that adds a very nice touch to the interface of the functionality.
I've looked into modifying the uploadFiles()-method in dropzone.js, but that seems drastic. I've also tried to figure out whether or not I can use the accept option in options but that seems like a dead end.
The two most similar problems with solutions are the ones linked below, where the first seems to be applicable in my case, but at the same time looks less "clean" than I would want to use.
The second one is for uploading images with a Base64 encoding.
1 - Simulating XHR to get ArrayBuffer
2 - Upload image as Base64 with Dropzone.js
So my question in a few less words is, when a file is added, how do I intercept this, convert the data to an arraybuffer, and then POST it using Dropzone.js?
This is a late answer to my own question, but it is the solution we went for in the end.
We kept dropzone.js just for the nice interface and some help functions, but we decided to do the actual file upload using $.ajax().
We read the file as an array buffer using the HTML5 FileReader
var reader = new FileReader();
reader.onloadend = function(e) {
resolve(e.target.result);
};
reader.onerror = function(e) {
reject(e.target.error);
};
reader.readAsArrayBuffer(file);
and then pass it as the data argument in the ajax options.
I recently came across this exact issue and so did some investigation into the Dropzone library.
I managed to correct the upload process for SharePoint/Office 365 by monkey patching the Dropzone.prototype.submitRequest() method to modify it to use use my own getArrayBuffer method that returns an ArrayBuffer using the FileReader API before sending it via the Dropzone generated XMLHttpRequest.
This enables me to continue to use the features of Dropzone API.
Only tested on a single auto upload, so will need further investigation for multi file upload.
Monkey patch
Dropzone.prototype.submitRequest = function (xhr, formData, files) {
getArrayBuffer(files[0]).then(function (buffer) {
return xhr.send(buffer);
});
};
getArrayBuffer
function getArrayBuffer(file) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onloadend = function (e) {
resolve(e.target.result);
};
reader.onerror = function (e) {
reject(e.target.error);
};
reader.readAsArrayBuffer(file);
});
}
After the file is uploaded into SharePoint, I use the Dropzone 'success' event to update the file with metadata.

First time file not uploading in blueimp Jquery File Upload

I am using Blueimp JqueryFileUpload, when i tried to upload my very first file its not uploading. But After i tried the same file or any file its working.
I can't figure out whats goes wrong for the very first upload.
While debugging i can found that the fileupload method not triggered for the first upload but followed consecutive uploads say second,third,.. its triggering
$('#fileUpload').fileupload({
url: 'home/upload',
dataType: 'json',
done: function (e, data) {
//do something
}
});
Are you generating the input file field after the page loads? I had the same issue because I forgot to initialize .fileupload() after the input field was appended.
Initialize .fileupload() method after form or form field is generated.
like
$('#fileupload'+rowNum).fileupload();
here $('#fileupload'+rowNum) is a dynamic form id.

Ember js RESTAdapter PUT request adds .json to the end

I've been trying to learn Ember and I have a question.
In my store I'am getting data from .json like below. I have tried without buildUrl function but cant load the json file, then found this solution on SO.
CocktailApp.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.extend({
bulkCommit: false,
url: "http://localhost:8888",
buildURL: function(record, suffix) {
var s = this._super(record, suffix);
return s + ".json";
}
})
});
Now comes my question: When I commit the chances (by pressing add to favs or remove from favs) RESTAdapter adds ".json" at the end of to PUT request. See the below code and screenshot
CocktailApp.CocktailController = Ember.ObjectController.extend({
addToFav: function () {
this.set('fav',true);
this.get('store').commit();
},
removeFromFav: function () {
this.set('fav',false);
this.get('store').commit();
}
});
I think thats why my PUT request can not be handled. But If I remove the builtURL function no json loaded at all. How can I resolve this problem?
Thanks
If the API endpoint url does not require .json at the end of it, then remove that line from your buildURL function. My guess is that the example code you got was consuming a ruby on rails api, or something similar.
remember, when you send a GET, PUT, POST, or DELETE to a url, that url needs to actually be a real endpoint. You can't just add extraneous stuff to it and have it still work.