How to upload image on server using ajax jquery? - javascript

Actually I'm trying to upload a image on server using ajax jquery?
My Code:-
$(function(){
$('#uploadFile').submit(function(){
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url : 'upload.php',
type : 'POST',
data : formData,
success : function(data) {
console.log(data);
alert(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="uploadFile">
<input type="file" id="file" />
<button type="submit">Submit</button>
</form>
Thankyou for your efforts!

$(function(){
$('#uploadFile').submit(function(){
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url : 'upload.php',
type : 'POST',
data : formData,
contentType: false, // You need to add this
processData: false,// You need to add this also
success : function(data) {
console.log(data);
alert(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="uploadFile">
<input type="file" id="file" />
<button type="submit">Submit</button>
</form>

Related

Send file to api using Ajax

Im trying to send file to api using ajax , but form-data always null in both cases mentioned below
<form id="myformdoc">
<input type="file" size="45" name="file" id="file">
</form>
<script>
$('#file').on("change", function () {
// var formdata = new FormData($('form').get(0));
let myForm = document.getElementById('myformdoc');
let formData = new FormData(myForm);
$.ajax({
url: url,
type: 'POST',
data: formdata ,
cache: false,
processData: false,
contentType: false,
success: function (color) {
;
},
error: function () {
alert('Error occured');
}
});
});
</script>
Any idea why form-data always null ?
Try adding multipart/form-data in contentType parameter.
You need to use
formData append to add files to your formData function.
Change your jQuery code to this below and it will work fine and you can get the files on your backend to save them.
If you have other inputs in your form you can append them as well if you like to.
formData.append('file', $(this)[0].files[0])
Demo:
$('#file').on("change", function() {
//Initialize formData
let formData = new FormData();
console.log($(this)[0].files)
formData.append('file', $(this)[0].files[0]) //append files to file formData
$.ajax({
url: 'url',
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(color) {
console.log(color);
},
error: function() {
alert('Error occured');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form enctype="multipart/form-data">
<input type="file" size="45" name="file" id="file">
</form>

Sending files and other data using ajax

I am trying to send data to server which includes files and strings with ajax. My code in jsp is:
<html>
...
<body>
...
<form id="data" method="post" enctype="multipart/form-data">
<input name="classroomID" type="hidden" value="1" />
<input type="file" name="file" size="30" id="file" />
<button>Submit</button>
</form>
<script type="text/javascript"
src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script type="text/javascript" src='sendUpload.js'></script>
...
</body>
</html>
And my sendUpload.js looks like this:
$(document).ready(function() {
console.log("here");
$("form#data").submit(function(ev){
ev.preventDefault();
console.log("Submitted");
var formData = new FormData($(this)[0]);
console.log(JSON.stringify(formData));
$.ajax({
url: "UploadServlet",
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
But the JSON data is empty. any suggestions? I am using java servlet.
What kind of errors are you getting? Looks like your jquery selector is wrong, i'd try changing this:
$("form#data").submit(function(ev){
To this:
$("#data").submit(function(ev){
Not really sure though, you should post the specific errors.
$(document).ready(function() {
$("form#data").submit(function(e){
e.preventDefault();
$.ajax({
url: "UploadServlet",
type: 'POST',
data: {
classroomID: $('input[name="classroomID"]').val(),
file: $('input[name="file"]').val()
},
success: function (data) {
alert(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
Does it work for you?
You can do this:
var formData = new FormData();
formData.append('classroomID', $('#classroomID').val());
formData.append('file', $('#file')[0].files[0]);
...and give your classroomID input field an id of 'classroomID'.
Also, you cannot inspect formData directly from the console so you will have to use this to debug:
for (var item of formData) {
console.log(item);
}

send uploaded files and inputs values with ajax

I'm trying to upload files with datas using ajax.
here is my html form :
<body>
<input type="text" id="name" value="test" />
<input type="file" id="pic" accept="image/*" />
<input id = "submit" type="submit" />
</body>
when I send the uploaded file alone with ajax it is working using new FormData();
var file_data = $('#pic').prop('files');
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'test.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response);
}
});
but Idon't know how to send the input 'name' with Data
var DATA = 'name='+name;
$.ajax({
url: "test.php",
type: "post",
data: DATA,
success: function (response) {
console.log($response);
},
});
Thanks

How to upload a file through ajax in struts2

<s:file name="excel" id="excel"/>
function saveData(){
vald();
var postData = $("#fname").serializeArray();
$("#fname")[0].reset();
$('<div class="success-tog" >Processing...</div>').prependTo('body').delay(1000);
$.ajax({type: "POST",url: "",data: postData success: sucFunc()});
Script Code
}
You can use formdata to uplaod code or any jquery file upload plugin
https://stackoverflow.com/a/204271/876739
You can see this post https://stackoverflow.com/a/41458116/876739
$(document).on('click', '#upload', function(e) {
e.preventDefault();
var fd = new FormData();
var file = $('#my_file')[0].files[0];
fd.append('file', file);
fd.append('userId', $('#userid').val());
console.log("hi");
$.ajax({
url: 'UploadPic',
data: fd,
type: "POST",
contentType: false,
processData: false,
success: function(dd) {
alert("sucessfully Uploaded")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="my_file">
<input type="hidden" id="userid" />
<input type="button" id="upload" value="Upload" />

how to upload image when its show 500 error in angularjs

i want upload image but its show below error how to solve this problem, because other format of html working fine ..i want use in angularjs
500 (Internal Server Error)
<input type="file" name="file" id="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
$scope.uploadFile = function(files) {
var fd = new FormData();
fd.append("file", files[0]);
$http.post(http://www.example.com/id/123, fd, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).success(res => {
var data = res.headers.get('application/json');
console.log(data);
}).error(function(err) {
console.log('sss');
});
};
but when i check use below format its working fine but i want response because i need save into database
<form action="http://www.example.com/id/123" method="post" enctype="multipart/form-data">
Upload: <input type="file" name="upload_image"><br/>
<input type="submit" value="submit">
</form>
its working for me.
<form id="data" method="post" enctype="multipart/form-data">
<input type="file" id="file" ng-model="files" name="upload_image">
<input type="submit" value="submit">
</form>
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:url,
type: 'POST',
data: formData,
async: false,
success: function (response) {
$scope.showimage= response.image_path;
},
cache: false,
contentType: false,
processData: false
});
return false;
});

Categories