0

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);
    }
});
Fai W
  • 105
  • 10

2 Answers2

2

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

uke
  • 893
  • 4
  • 10
  • Does the workaround you're referring means I can use a JSON of which the encoded image is part of the JSON. – Fai W Dec 16 '20 at 18:12
  • you might write js to convert your file into data base64 using this https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL then you can pass to query param and or json. Consider there is a limit of bytes in url, so thats not an option for big images https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers#:~:text=Short%20answer%20%2D%20de%20facto%20limit,of%20client%20and%20server%20software. – uke Dec 16 '20 at 18:15
  • Given that there is length limitation for query string, GET is definitely not an candidate. Is there any length limitation for POST operation? – Fai W Dec 16 '20 at 19:11
  • Not on the browser side but it depends on the web server. I. E. Php had file upload default about 2mb – uke Dec 16 '20 at 21:31
0

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

Kamilg732
  • 13
  • 2
  • 4