Multiple file upload isn't sending any data to server - javascript

I want to upload multiple file upload.
I have this on client side :
$(document).on( "click", ".save-button", function () {
var data = new FormData();
data.append('title', $(this).parent().parent().find("#title_place").val());
$.each($(this).parent().parent().find("input[type='file']")[0].files, function(i, file) {
data.append('file', file);
});
$.ajax({type: "POST",
url: 'save_view.php',
data: data,
success : viewSaveCallBack,
cache: false,
contentType: false,
processData: false,
});
});
I checked all the data in the debuger, and it is working properly. To see this I displayed the value of
$(this).parent().parent().find("#title_place").val()
And
$(this).parent().parent().find("input[type='file']")[0].files
Then, when I try to var_dump $_FILES or $_POST on server side, it's empty.
Same thing with a debugger.
I tried also with
data.append('files[]', file);
When I try to upload a single file (in another input, not exactly the same code), that is working fine.
The html of the input is this one :
<input type=\"file\" multiple directory webkitdirectory allowdirs class=\"form-control input\" id=\"marzipano\">
And it is added dynamically to the DOM.
When I upload a single file, that is working fine.
It is not a duplicate of Sending multipart/formdata with jQuery.ajax since I already use a FormData object, and my code is the same as the answer. It is still not working as intended.

Try to do:
var files = $(this).parent().parent().find("input[type='file']")[0].files;
for(var i=0; i<files.length; i++) {
data.append('file['+i+']', files[i]);
}
and in PHP you might get files via $_POST["file"]

My code is working actually, problem was that post_max_size in the php.ini was too low.

Related

How to send big files using ajax?

So currently I'm working on a simple project where users gets to upload an image to server. Before I mention my problem here is how I'm doing it:
Client:
var dataURL = sendingcanvas.toDataURL("image/*");
var imagedatatosend = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
formdata = {
'image': imagedatatosend
};
$.ajax({
url: '../receive',
type: 'POST',
data: formdata,
encode: false,
success: function(result){
alert(result);
}
});
FYI: imagedatatosend size is lower than 5MB and contains exactly the file data selected.
Basically What happens Is that users select an image using <input type="file" tag Then I'm setting that selected file drawn in a canvas to convert it to base64 and send it to server.
Java Server:
String datareceived = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
byte[] bImg = Base64.decodeBase64(datareceived.getBytes("UTF-8"));
FileOutputStream fos = new FileOutputStream("hi.jpg");
fos.write(bImg);
fos.close();
I think I might not need to explain what the code above does. But I'm facing some serious performance problem I mean It takes some huge time to write the data to hi.jpg file, even if I try System.out.println(datareceived); It takes seconds for my mouse click to respond on server console.
I don't know why is it happening, Do I need to send the image data as multipart or what?
All replies are appreciated and Thanks in Advance:)
Use XMLHttpRequest and FormData to append the file. It will be sent using multipart and chunked appropriately.
See: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

Cannot upload a file and call a network server via AJAX Jquery from a ASP.NET WEB forms application

I need to access a gateway server via its IP address. The gateway is accessed via http. I need to first upload a file and then make the call on the client.
HTML:
<asp:FileUpload ID="FileUploadExcelImport" runat="server" Width="412px" ToolTip="Select file to upload."/>
<asp:Button ID="CallGateway" Text="Call Server" runat="server" />
JQUERY/AJAX code:
var form = $("#form1");
var model = new window.FormData(form);
var file = $("#<%=FileUploadExcelImport.ClientID%>").get(0);
var files = file.files;
// Add the uploaded image content to the form data collection
//var data = new FormData();
for (var i = 0; i < files.length; i++) {
model.append(files[i].name, files[i]);
}
$("#<%=CallGateway.ClientID%>").click(function (evt) {
evt.preventDefault();
var ajaxRequest = $.ajax({
type: "POST",
url: "http://10.242.83.21/",
processData: false,
data: model,
contentType: "multipart/form-data",
//dataType: "json",
success: function (result) {
var jsonParse = $.parseJSON(result);
alert("success");
},
error: function (badresult) {
var jsonParse = $.parseJSON(badresult);
alert("failure")
}
});
)};
)};
Upon reviewing the NETWORK in the IE browser I don't see any file being sent in the REQUEST BODY. contenttype = "multipart/form-data". The file can be a MS WORD, JPEG, PNG, TXT file being uploaded. But the return is a JSON Object containing a message. This is from a ASP.NET Web forms application. I have looked at many sites but cannot find what is wrong with my AJAX calling method above.
I tried doing the model like this:
var form = $("#form1");
var model = new window.FormData(form);
as it did not work changed it to var model = new window.FormData();. It still did not work. I am not able to see the file being passed in the Request.Body in the NETWORK of the IE Browser. We use IE 11 browser.
I have already been through these sites:
http://digipiph.com/blog/submitting-multipartform-data-using-jquery-and-ajax
http://midhundevasia.com/article/sending-multipartform-data-using-jquery-ajax-snippet-2415/
http://www.codeproject.com/Articles/806075/File-Upload-using-jQuery-AJAX-in-ASP-NET-Web-API
http://www.binaryintellect.net/articles/f2a2f1ee-e18a-416b-893e-883c800f83f4.aspx
https://weblog.west-wind.com/posts/2010/Sep/07/Using-jQuery-to-POST-Form-Data-to-an-ASPNET-ASMX-AJAX-Web-Service
Form has enctype="multipart/form-data" but Request Content-Type is application/x-www-form-urlencoded; charset=UTF-8
Also I do not want to add an enctype and action to my existing form on the HTML side. As it will impact my existing page.
Please tell me what I am doing wrong. Please give me suggestions.

Multipart or base64 for AJAX file uploads?

I'm writing a single page application with EmberJS and need to upload a few files.
I wrote a special view, that wraps the file input field and extracts the first file selected. This lets me bind the File-Object to a model-attribute.
Now I have to choose.
I can write a special file transform, that serialises the File-Object to base64 and simply PUT/POST this.
Or I can intercept the RESTAdapter methods createRecord and updateRecord to check every model for File-Objects and switch the PUT/POST requests to multipart/form-data and send it with the help of FormData
Does one of these directions pose significant problems?
I've had to evaluate the same concern for a Restful API I'm developing. In my opinion, the most ideal method would be to just use the RESTAdapter with base64 encoded data.
That being said, I had to use the multipart/form-data method in my case, because the data transfer is 30% higher when you base64 encode the file data. Since my API would be have to accept large (100MB+) files, I opted to have the POST method of the API to receive multipart form data, with the file and json data being one of the POST variables.
So, unless you need to upload large files like in my case, I'd recommend always sticking to the REST methods.
Just ran into this myself, and ended up using a simple jQuery AJAX call using the FormData object. My multi-select implementation (where one can drop multiple files at once) looks like this:
filesDidChange: function() {
// Get FileList
var $input = this.$('input'),
fileList = $input.get(0).files;
// Iterate files
for (var i = 0; i < fileList.length; i++) {
var file = fileList[i],
formData = new FormData();
// Append information to FormData instance
formData.append('attachment[title]', file.name);
formData.append('attachment[file]', file);
formData.append('attachment[post_id]', this.get('post.id'));
// Send upload request
Ember.$.ajax({
method: 'POST',
url: '/attachments',
cache: false,
contentType: false,
processData: false,
data: formData,
success: makeSuccessHandler(this),
error: makeErrorHandler(this)
});
}
// Notify
this.container.lookup('util:notification').notify('Uploading file, please wait...');
// Clear FileList
$input.val(null);
},

Yii framework: Save uploaded file

I'm using Yii framework for developing website.
Here, I have a problem in save image file which uploaded to server.
Here is the code which I used for uploading image.
<input type="file" onChange="uploadImage(this);">
function uploadImage(obj) {
var request_url = server_url + "uploadImage";
var formData = new FormData();
formData.append("photo", obj.files[0]);
$.ajax({
url: request_url,
type: 'POST',
data: formData,
processData: false,
contentType:false
});
}
And in server part, I can see the file has uploaded but can't get the file.
public function actionUploadImage() {
if (ISSET($_FILES['photo'])) {
var_dump('is set photo');
$temp = CUploadedFile::getInstanceByName('photo');
var_dump($temp);
}
}
It returns "is set photo" and "array(0){}".
Please help me.
You are uploading images using jquery/ajax. You need to include jquery and their corresponding function.
Here is one of tutorial to upload images using jquery -
http://www.9lessons.info/2013/09/multiple-ajax-image-upload-jquery.html
You could google for other tutorials.

Unable to upload file using AJAX

I am trying to upload a file through AJAX. I have searched over a lot but found examples using form submit only, but I can not use form submit. I have tried several examples but nothing reaches my server. When I tried this link, it worked but again it was through a form submission.
Here is the piece of code relevant to the context
JS Code
function _upload(filedata) {
$.ajax({
url: './myURI',
data: filedata,
type: 'POST',
contentType: 'multipart/form-data',
mimeType: 'multipart/form-data', //Property added in 1.5.1
success: function (data) {
alert(data);
}
});
}
$("#cpc-uploadBtn").click(function (evt) {
var data;
data = new FormData();
data.append('file', $('#cpc-upload')[0].files[0]);
_upload(data);
});
HTML Part
<input id="cpc-upload" name="file" type="file" />
<button id="cpc-uploadBtn" type="button">Upload</button>
Edit
Is there any other way to do this without using form submit and formdata?
Assuming that you are using Safari/FireFox (only those support FormData), you need to modify your $.ajax call:
$.ajax({
url: './myURI',
data: filedata,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {
alert(data);
}
});
Seeting contentType option to false will force jQuery not to add a Content-Type header for you (otherwise the boundary string will be missing from it). Also the processData flag must be set to false so jQuery will not try to convert your FormData into a string.
Now if you know that your clients are using HTML5 you should try using new JavaScript File API - check following articles:
Working with files in JavaScript, Part 1: The Basics
Working with files in JavaScript, Part 2: FileReader
Working with files in JavaScript, Part 3: Progress events and errors
Working with files in JavaScript, Part 4: Object URLs
Working with files in JavaScript, Part 5: Blobs
In all other cases you are forced to use custom plugins, for example:
Uploadify
jQuery Form Plugin
I suppose currently FormData objects are only supported in Safari/Firefox, it has not been adopted by most of the browsers yet.
I recently struggled a lot finding ajax file uploader for asp.net and I am currently using this one in my project:
https://github.com/valums/file-uploader
there is a small alternative if you want to use
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing soinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
you can find the plugin here

Categories