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...
});
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
I would like to send the form in its entirety, using ajax.
The form has an Id which is 'FormId'.
const Url = '/CV/AutoSave/';
var testForm = $('#FormId');
var cvForm = new FormData(testForm[0]);
$.ajax
({
url: Url,
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: cvForm,
success: function (result) {
console.log(result.Id)
}
});
When debugging the code I can see that testForm is equal to the entire form.
var cvForm = new FormData(testForm[0]);
Is empty for some reason.
The form has many fields, so I hope it is possible to send the entire form, instead of defining every single field in js before sending them.
Thanks in advance.
When you use FormData, the content type should be multipart/form-data, not application/x-www-form-urlencoded. You should also use processData: false to prevent jQuery from trying to serialize the FormData object.
$.ajax
({
url: Url,
type: "POST",
contentType: "multipart/form-data",
processData: false,
data: cvForm,
success: function (result) {
console.log(result.Id)
}
});
If the form doesn't have any file uploads, you can use $('#FormId').serialize() to serialize it in URL-encoded format, then your $.ajax call would work. You don't need the contentType option, it defaults correctly.
You need to set contentType to false so proper Content-Type header with correct boundary will be set. Also set processData to false to prevent jQuery serializing data
const Url = '/CV/AutoSave/';
var testForm = $('#FormId');
var cvForm = new FormData(testForm[0]);
$.ajax({
url: Url,
type: "POST",
processData: false,
contentType: false,
data: cvForm,
success: function (result) {
console.log(result.Id)
}
});
I have following html
<form id="submit-form">
<input type="file" id="resume" name="resume[]" class="inputFileHidden" multiple>
<input type="submit">
</form>
I am uploading files using ajax using formdata. The thing is that I don't want to send all files in one go using ajax. Instead I want to send single file per ajax request.
To upload files I am using following jQuery code
$('#submit-form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var url = "upload-files.php";
$.ajax({
url: url,
type: 'post',
data: formData,
success: function(response) {
alert(response);
},
cache: false,
contentType: false,
processData: false
})
})
You can just use forEach method of FormData:
$('#submit-form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var url = "upload-files.php";
formData.forEach(function(entry) {
if (entry instanceof File) {
var fileForm = new FormData()
fileForm.append('resume', entry)
$.ajax({
url: url,
type: 'post',
data: fileForm,
success: function(response) {
alert(response);
},
cache: false,
contentType: false,
processData: false
})
}
})
})
I know, the topics aren't missing on this subject but bear with me. I'd like to upload a file to the server using Ajax or an equivalent.
# html
<form method="post" id="Form" enctype="multipart/form-data">
{% csrf_token %} # django security
<input id="image_file" type="file" name="image_file">
<input type="submit" value="submit">
</form>
# javascript
$(document).on('submit', '#Form', function(e){
e.preventDefault();
var form_data = new FormData();
form_data.append('file', $('#image_file').get(0).files);
$.ajax({
type:'POST',
url:'my_url',
processData: false,
contentType: false,
data:{
logo:form_data,
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), # django security
},
});
});
# views.py (server side)
def myFunction(request):
if request.method == 'POST':
image_file = request.FILES
...
...
I guess there's an issue with the way I configured the ajax function since on debug mode, every data are returned except the logo.
Am I doing something incorrectly?
The below method works for me, it will submit all form value as serialize(). You will get all form input's inside request.POST and logo request.FILES
Try this:
$(document).on('submit', '#creationOptionsForm', function(e){
e.preventDefault();
var form_data = new FormData($('#creationOptionsForm')[0]);
$.ajax({
type:'POST',
url:'/designer/results/',
processData: false,
contentType: false,
async: false,
cache: false,
data : form_data,
success: function(response){
}
});
});
Update:
basically async:false will do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.
While cache will force browser to not cache uploaded data to get updated data in ajax request
Official Documentation here
Looking back, the older answer is unpractical and not recommended. asnyc: false pauses the entire Javascript to simply upload a file, you are likely firing other functions during the upload.
If you are using JQuery solely for the use of ajax, then I recommand using axios:
const axios = require('axios');
var formData = new FormData();
formData.append('imageFile', document.querySelector('#image_file').files[0]);
axios({
method: 'post',
url: 'your_url',
data: formData,
headers: {
"X-CSRFToken": CSRF_TOKEN, # django security
"content-type": "multipart/form-data"
}
}).then(function (response) {
# success
});
Axios Documentation
Jquery/Ajax answer:
var formData = new FormData();
formData.append('imageFile', $('#image_file')[0].files[0]);
formData.append('csrfmiddlewaretoken', CSRF_TOKEN); # django security
$.ajax({
url : 'your_url',
type : 'POST',
data : formData,
processData: false,
contentType: false,
success : function(data) {
# success
}
});
Jquery/Ajax Documentation