Is it Possible to Upload Image Using HTTP GET - javascript

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

Related

How can I send a file and a string to my backend C# from JQuery Ajax?

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";
}

How to Send image data with other data to java backend with http post in JS

IAM trying to develop a offline PWA app .I have a image blob data which I want to send to java backend.
function callAjax(data){
$http({
method: 'POST',
url: "./WQF00069/update.app",
cache:false,
async:false,
params:data,
data: {} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
}).success(function(data) {
Flash.create('info', ' Update Success Fully ', 'large-text');
}).error(function(response){
console.dir(response);
Flash.create('danger','There is a Problem.Contact With Administrator', 'large-text');
});
}
After send the image data in params no data receive in java backend.Please help
Convert your image to text-based encodings ( Personally I would use base64) and send it with a POST request to your backend Java API.
I am sending this image data through ajax to backend.I also conver it in base 64 encode. But still problem .I think large data can not send through ajax.Here is my full code
//***After click on upload button******************//
vm.upload= function(state_cd,dist_cd,blk_cd,pan_cd,src_typ_cd,src_cd,src_nm,m_lat_val_degree,m_long_val_degree,src_img,imageContent){
var imageall=null;
var fd=null;
var blob=null;
var url=null;
//***************imageContent blob content from indexd db and transfer in image *******************************************************************//
getImageUrlFromBlob(imageContent).then(function (result) {
imageall = result.replace(/data:;base64,/, 'data:image/gif;base64,');
//var block = imageall.split(";");
// var realData = block[1].split(",")[1];
// blob = b64toBlob(realData,"image/gif");
// var reader = new FileReader();
// reader.readAsText(blob);
//var image= reader.result;
var data={'mst.stateCd':state_cd,'mst.distCd':dist_cd,'mst.blkCd':blk_cd,'mst.panCd':pan_cd,'mst.userId':$rootScope.userId,'mst.srcTypCd':src_typ_cd,'mst.srcCd':src_cd,'mst.srcNm':src_nm,'mst.mLatValDegree':m_lat_val_degree,'mst.mLongValDegree':m_long_val_degree,'mst.srcImg':src_img,'mst.imageContent':imageall};
callAjax(data);// send image data to backend throgh ajax
});
}
//************************Ajax call*****************************************************//
function callAjax(data){
$http({
method: 'POST',
url: "./WQF00069/update.app",
cache:false,
async:false,
params:data,
data: {} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
}).success(function(data) {
Flash.create('info', ' Update Success Fully ', 'large-text');
}).error(function(response){
console.dir(response);
Flash.create('danger','There is a Problem.Contact With Administrator', 'large-text');
});
}
$("form[name='uploader']").submit(function(e) {
var formData = new FormData($(this)[0]);
$.ajax({
url: "page.jsp",
type: "POST",
data: formData,
success: function (msg) {
alert(msg)
},
cache: false,
contentType: false,
processData: false
});
e.preventDefault();
});
follow this How to send image to PHP file using Ajax?

Send form using javascript/jquery

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)
}
});

How to add ajax parameters?

Faced with such a problem that you can't add parameters to ajax request, because there is a "Form Data" and it does not work to add more options. When you add in the parameter 'data' another variable, the error occurs. How to do that would be to post a file and parameters in one request?
Forgive the mistake, error or no, the php file simply does not output anything, rather empty values
//Here the file is sent without problems, but the parameters no more don't accept php file, nothing displays in the result
var fd = new FormData();
fd.append('file', input[0].files[0]);
$.ajax({
url: "/controllers/createNewsController.php",
data: fd,
type: "POST",
processData: false,
contentType: false,
success: function(data) {
$(".news .containers").append(data);
}
});
//When this code runs the PHP file won't take anything, although I was expecting the output variables and the file. Using var_dump, $_POST and $_FILES displays array(0){}
var fd = new FormData();
fd.append('file', input[0].files[0]);
$.ajax({
url: "/controllers/createNewsController.php",
data: {fd, title:newsHeader, description:description, hashTag:hashTag, themeHashTag:themeHashTag, viewNews:viewNews},
type: "POST",
processData: false,
contentType: false,
success: function(data){
$(".news .containers").append(data);
}
});
//Similarly, nothing appears in the php file
var fd = new FormData();
fd.append('file', input[0].files[0]);
$.ajax({
url: "/controllers/createNewsController.php",
data: {fd:fd, title:newsHeader, description:description, hashTag:hashTag, themeHashTag:themeHashTag, viewNews:viewNews},
type: "POST",
processData: false,
contentType: false,
success: function(data){
$(".news .containers").append(data);
}
});
Just like you have appended the file, you can append more data into it like:
fd.append('file', input[0].files[0]);
fd.append('var1', val1);
fd.append('var2', val2);

ajax form submit redirect like a not ajax form

I have this code that I use to submit a form with a attachment file
$("#career_form").submit(function(e){
var this_current = $(this);
var formData = new FormData(this_current[0]);
var url = this_current.attr("action");
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
e.preventDefault();
});
but the form keeps redirecting me to its destination file "url in the action" like it wasn't an ajax submission but if I replace the 'data' argument with
data: $(this).serialize();
it works (ajax submit), any ideas, help, suggestions, recommendations?
give that e.preventDefault(); at the beginning of the function.
jQuery trys to transform your data by default into a query string, but with new formData it throws an error.
To use formData for a jquery ajax request use the option processData and set it to false like:
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
processData: false,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
Thats the reason why it works with serialize, but not with formData in your example.
The e.preventDefault works correctly, but if there is an error before it will not work. By placing the e.preventDefault at the top of your function it will allways prevent the action, no matter if there is an error in later code or not.
You can edit the var formData = new FormData(this_current[0]); in your code and use the below line:
var formData = new FormData(document.querySelector("#career_form"));
Also, if you are using multipart form to send files in your form, you need to set following parameters in your ajax call.
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
Hope this helps. See more about using formData here.
Try this:
$("#career_form").submit(function(e){
e.preventDefault();
var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
url: "change-status.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response){
if(response){
alert("successfully sent");
}
}
});
});

Categories