This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 5 years ago.
I create jersey REST server and receive file upload.
This is the tutorial I follwed: https://gist.github.com/aitoroses/4f7a2b197b732a6a691d
Everything works fine when I try to test the server with Postman. I chose Body, form-data, key: file, value: my picture jpeg
What I try to do is to upload file using form html and jquery
Here is my form
<form>
<input id="imgFile" type="file" accept="image/*" value="Add file">
<input id="buttonPostReview" class="buttonSend" type="submit" value="Submit">
</form>
and here is my jquery
var postFile = function(e) {
e.preventDefault();
var imgFile = $('#imgFile').val();
var upLoalImgUrl = endPointUrl + 'webresources/photo';
console.log(imgFile);
console.log('uploading..');
$.ajax({
type: "POST",
url: upLoalImgUrl,
data: imgFile,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (returnData) {
console.log(returnData);
alert("Data Uploaded: ");
}
});
}
But I got error 415 - Unsupported Media Type
Can you show me how to upload file using jquery? I try to do some search but I can find the way to do this
$(...).val() doesn't get a file from a file input, it just returns the name of the file. You need to do $("#imgFile")[0].files[0] and send the file with FormData:
var data = new FormData();
data.append('file', $("#imgFile")[0].files[0]);
$.ajax({ data: data, ... });
Related
My UI has one input for uploading file and one input for the file's name.
I want to get both file and its name from user at the same ajax request and upload the file with the gotten name to my server.
the question is how can I get both file (binary) and the file's name from user at the same request ?
here is my try but results in 400 error.
Function in C#:
public IActionResult UploadImage(IFormFile upload, string fileWithName)
{
//some code here
}
and here is my ajax:
$("#startUploading").on("click",function() {
var fileInput = $.trim($("#myfile").val());
var formData = new FormData();
formData.append('upload', $('#myfile')[0].files[0]);
formData.append('pathWithName', $("#fileAddressUploadTo").val());
$.ajax({
url: apiUrl+'/api/V1/Servers/UploadImage',
type: 'POST',
data: formData,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem('token'));
},
cache: false,
processData: false,
contentType: false
});
});
400 error means bad request, but per my test I found it worked for me. So I'm afraid the issue in your code may relate to $('#myfile')[0].files[0], see my code below
<div>
<input type="file" id="uploadFile" />
<button id="btn4">upload</button>
</div>
$("#btn4").click(function(){
var form = new FormData();
var temp = $('#uploadFile').prop('files');
form.append("file",temp[0]);
form.append("name","myFile");
console.log(form);
$.ajax({
url: 'https://localhost:44321/hello/upload',
type: 'POST',
data: form,
cache:false,
contentType:false,//stop jquery auto convert form type to default x-www-form-urlencoded
processData:false,
success: function (d) {
alert(d)
}
});
});
public string upload(IFormFile file, string name) {
return "hello";
}
I've been using the following code to upload image to server. Is it possible to change it to pass file data using an object instead of form data and using GET instead of POST.
var uploadfileinfo = document.getElementById("upload-file-info").value;
var file_data = $('#a_imgfile').prop('files')[0];
var a_imgfile = document.getElementById("a_imgfile");
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
async: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
alert(response);
},
error: function(err) {
alert(err);
}
});
Browser file upload will send form multipart contenttype, you cant send content type in GET request
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
If you are looking for some workaround you can use some base64 encoder and pass your image to url query param
In GET request you can only get data or pass query paramerters. If you want to upload image change any other data it must be in POST request
Read more https://www.w3schools.com/tags/ref_httpmethods.asp
Using Jquery, when i try to call external API by sending any file. I'm facing 415 Unsupported Media Type error. I'm trying to send my document using FormData() and header data in beforeSend() function. Suggest me correct way of sending data.
<div id="folder-browser">
<input type="file" id="file-select" name="photos" />
<button id="myButton" value="click me">click me</button>
</div>
$("#myButton").click(function() {
var myData = new FormData();
var myFile = document.getElementById("file-select");
myData.append(myFile.files[0].name, myFile.files[0]);
$.ajax({
url: 'http://10.96.45.179/RightFax/API/attachments',
data: myData,
processData: false,
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic c3lzYWRtaW46cGFzc3dvcmQtMQ==');
},
type: 'POST',
success: function(result) {
console.log(result);
return result;
}
});
});
Query 2: If my document is present in URL. please let me know How can I pass the URL as a file source.
for Example:
filepath = 'http://seekvectorlogo.com/wp-content/uploads/2018/02/opentext-vector-logo-small.png';
I need to pass this file source to my external API.
When uploading binary data in a FormData object you need to set contentType: false:
$.ajax({
url: 'http://10.96.45.179/RightFax/API/attachments',
data: myData,
processData: false,
contentType: false,
// your other settings...
});
am trying to upload files and I discovered that ['tmp_name'] is empty if I select .mp4 file, .pdf and even flv. it works fine with image and doc files and other..
my html
<form id="MaterialUpload" action="#" method="post" enctype='multipart/form- data' class="form-horizontal form-row-seperated">
<input type="file" name="fileUpload" class="form-control" />
// javascript posting it via ajax
var formData = new FormData(this);
$.ajax({
url: '../CONTROLLER/MaterialAPI.php?CreateCategory=true=',
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
$(".auctncr").html(data);
},
// php
echo $_FILES['fileUpload']['tmp_name'];
In your php.ini change upload_max_filesize.
upload_max_filesize = 2M replace 2 with 6 or 10
I have a form, with a file input, that submits just fine when I use the default action to submit the form. But, when I use JQuery and AJAX to make the call to the PHP file, it does not seem to get the file. Is there something that I need to add for sending files through JQUERY/AJAX?
My HTML:
<form id="photo-form" enctype="multipart/form-data" method="post" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="5000000"/>
<input type="file" class="upload-input" name="upload-new-input" autocomplete="off"/>
<input type="submit" name="submit" value="submit/>
</form>
My JQuery:
$(document).ready(function() {
$("#photo-form").submit(function(e) {
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "uploadcover.php",
data: dataString,
async: false,
success: function(data) {
alert(data);
}
});
});
});
You can use FormData to upload file with data
Here is sample code
JQuery
$("#photo-form").submit(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "uploadcover.php",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(data) {
alert(data);
}
});
return false;
})
You can get it on PHP
PHP CODE
$Img = $_FILES['upload-new-input'];
You can see tutorial Uploading files with jquery ajax
Hope It helps you :)
You cannot access file directly.
You can use a plugin, to do this for you, i.e. https://github.com/blueimp/jQuery-File-Upload
Also, in html5 it is possible to access a file from file input as a blob. You can than send it using formData.
More info here: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects