FormData add file doesn't work - javascript

I have form:
<form enctype="multipart/form-data" action="" method="post" id="sendInvoiceForm">
<input type="text" value="Some text">
<input name="file[]" type="file" multiple/>
<input type="button" id="upload" value="Upload File" />
</form>
My js:
$('#upload').click(function(e) {
e.preventDefault();
var formData = new FormData();
formData.append('files',$("#sendInvoiceForm")[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
When I try to get my 'files' in php I get only [object HTMLFormElement]
How can I get my files on php?
But if I create my formData as :var formData = new FormData($("#sendInvoiceForm")[0]);
I can find my files in _FILES, but I need give name for this array.
How can I solve this problem? Thanks

The issue is because you're appending the form DOM Element to the FormData, not the file data. Instead, you should access the files array of that object:
formData.append('files', $('#sendInvoiceForm input[type="file"]')[0].files[0]);
As there can be multiple files selected, you'll need to loop through them:
$('#sendInvoiceForm input[type="file"]')[0].files.forEach(function(file) {
formData.append('files', file, file.name);
});

Related

Get CKeditor Value Using FormData Object

below is my html form
<form id='add'>
<input type="text" name="title">
<textarea id="usingckeditor" name="content"></textarea>
<input type="file" name="file">
<button id="save">save</button>
</form>
and here is my javascript
$("#save").on('submit',(function(e) {
$.ajax({
url: "blog/saveblog.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
}
});
})
i'm using new FormData() to send data to saveblog.php, and saveblog.php working to upload image and get value of $_POST['title'], but $_POST['content'] is empty
how FormData to get content of textarea(that using ckeditor)?
Buttons don't have submit events, you have to bind the submit event to the form, also you have to prevent the form from submitting since you're using ajax to post the data.
CKEditor manages its own content so it's not in the textarea, you can get it by calling getData() on the CKEditor instance
<form id='add'>
<input type="text" name="title">
<textarea id="usingckeditor"></textarea>
<!-- remove name attribute so it will not pollute form data object -->
<input type="file" name="file">
<button id="save">save</button>
</form>
$("#add").on('submit',(function(e) {// attach form to submit event
e.preventDefault(); //prevent the form from submitting
var data = new FormData(this);
//add the content
data.append('content', CKEDITOR.instances['usingckeditor'].getData());
$.ajax({
url: "blog/saveblog.php",
type: "POST",
data: data,
contentType: false,
cache: false,
processData:false,
success: function(data){
}
});
})
You might use:
$(form).trigger('form-pre-serialize');
And then create new FormData()
Add this before ajax call:
var data = new FormData([form]);
data.append('[textarea_name]', CKEDITOR.instances['textarea_id'].getData());

Uploading data and files in one form using Ajax PHP?

I'm using jQuery and Ajax for my forms to submit data and files but I'm not sure how to send both data and files in one form?
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
I was planning to use FormData as below
var formData = new FormData($(this)[0]);
but figured out that it does not work in IE<10 and which is not accepted. Is there any other approach for same?
This block should work for you.
$.ajax({
url: 'url',
type: 'POST',
async: true,
dataType: "json",
data: $('#data').serializeArray(),
error: function (a, b, c) { onError(a, b, c, parameters); },
success: function (data) { onSuccess(data, parameters); }
});
You can do like this in php instead of using form data,
Serialize you form data and send through ajax, like,
$.ajax({
type: 'post',
url: 'post.php',
data: $('#form').serialize(),
success: function () {
}
});
});
using $('#form').serialize() you can send your all form data to php.
I hope it helps,
function savedata(){
var vacancy_desc = CKEDITOR.instances['vacancy_desc'].getData();
var file_data = $('#fileupload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('vacancy_records',vacancy_records);
form_data.append('vacancy_desc',vacancy_desc);
$.ajax({
url:pathname,
method:"POST",
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data:form_data,
cache:false,
success:function(datas){
alert('Updated successfully !');
return false;
}
});
}

Spring Boot and jQuery file upload : Unsupported media type

I am trying to upload a csv file with spring boot 1.2.0 REST controller and jQuery ajax. When I send the post request, I keep getting 415:Unsupported Media type error. Here is my form:
<form id="upload_form">
<div id="message">
</div>
<br/>
<div class="row" id="upload-file-div" style="display: none">
<div class='col-sm-3'>
<label>Select File</label>
<input type="file" name="file">
</div>
<div class='col-sm-3'>
<input type="button" id="file-upload" class="btn btn-primary" value="Upload" onclick="uploadFile()"/>
</div>
</div>
</form>
Here is my method to upload file:
function uploadFile(){
var response = api.uploadCSV($("#upload_form"));
if(response.status === 'OK'){
$("#message").css('color', 'green');
}else{
$("#message").css('color', 'red');
}
$("#message").html(response.message);
}
Here is the actual jQuery POST:
upload: function (url, form, ignoreSuccess) {
var response = null;
if (!this.validate(form)) {
var array = form.serializeArray();
alert(array);
var formData = new FormData(form);
console.warn(formData);
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,
cache: false,
contentType: false,
processData: false,
async: false,
beforeSend: function (request) {
if (api.getSession() !== null) {
request.setRequestHeader("Authorization", "Bearer " + api.getSession().bearer);
}
},
success: function () {}
}).done(function (msg) {
response = msg;
});
}
return response;
}
Following is my controller:
#RequestMapping(consumes = "multipart/form-data", method = RequestMethod.POST,
value = "/upload/twitter", produces = MediaType.APPLICATION_JSON_VALUE)
public Response<String> uploadCsv(CsvUploadModel form) {
//Code
}
I have both MultipartConfigElement and MultipartResolver annotated in my spring boot class. I am using spring boot 1.2.0. When I send the post request with PostMan (chrome extension), it works as expected. However, when I try the above jquery code, it keeps throwing unsupported media type error.
Following things I have tried:
Playing around content-type header, finally I have set the contentType to false.
Using form.serializeArray(), iterating over it and appending individual elements into formData.
Sending the form object instead of form data.
Can anyone please help me with this? Thanks in advance.
You can append your file input in your formData; the following changes needs to be made:
This:
<input type="file" name="file">
Should be:
<input type="file" name="file" id="file">
And in your ajax code, this:
var formData = new FormData(form);
console.warn(formData);
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,
Should be:
var formData = new FormData();
formData.add("file",$('#file')[0].files)
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,
Or:
var formData = new FormData(form[0]);
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,

Upload File jQuery ajax MVC

I'm writing application where I need to upload file ajax I used jQuery.form library but the action go to the controller with empty list of files I don't know why here is my code html:
<form id="well-log-form" method="post" enctype="multipart/form-data">
<div class="fileUpload btn btn-primary">
<span>Well Logs</span>
<input type="file" id="well-logs" class="upload" />
</div>
</form>
and Js Code is :
document.getElementById("well-logs").onchange = function () {
var _url = "/Importer/WellLogUpload";
var options = {
beforeSubmit: showRequest,
url: _url,
type: 'post'
};
$('#well-log-form').ajaxSubmit(options);
};
function showRequest(formData, jqForm, options) {
return true;
}
function showResponse(responseText, statusText, xhr, $form) {
// $("body").append(responseText);
}
could any one help, I think it should work but I don't know why it is not working.
try this in jquery, it will post your file.
//#file is the id of { <input type="file" id="file"> }
$("#file").change(function () {
var file_data = $(this).prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data)
$.ajax({
url: "your url",
type: "post",
data: form_data,
contentType: false,
processData: false,
success: function (path) {
//on success
}
});
});

submit a form via ajax

I have this form:
<form id="ugaForm" method="POST" action="/url/upload" target="myFrame"
enctype="multipart/form-data">
Please select a file to upload : <input id="file" type="file" name="file" />
<input type="button" onclick="submitF()" value="upload" />
</form>
when submitting normally it works perfectly.
I need an ajax post to imitate this exact form submission.
This code doesnt work:
function submitF() {
debugger;
var mfile = $("form#ugaForm")[0].file;
var fd = new FormData();
fd.append( 'file', mfile);
$.ajax({
url: 'http://localhost/url/upload/',
data: JSON.stringify({ 'objectData' : fd}),
cache: false,
contentType : false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
If you are submitting something through AJAX then why are you putting it into the form. Just remove the form and keep the other things which were inside it so that it would become like this:
<div id="ugaForm">
Please select a file to upload : <input id="file" type="file" name="file" />
<input type="button" onclick="submit()" value="upload" />
</div>
And the JS would be this:
function submitF() {
debugger;
var mfile = $("#ugaForm")[0].file;
var fd = new FormData();
fd.append('file', mfile);
$.ajax({
url: 'http://localhost/url/upload/',
data: JSON.stringify({
'objectData': fd
}),
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
alert(data);
}
});
}
Hope it helps.

Categories

Resources