-1

I am trying to upload a image as Avatar photo to the server through the Web-API.

Anyone can explain how to insert the image URL into the data by current user id has token?

I have already done $.getJSON (url,... I can read and append them wherever I wanted.

I have something like this:

user_id=1

/api/images/upload_form/avatar

/api/users/update_user_info

1. How can I attach the image file and post it through Web-API with jQuery?

2. And How can I re-upload(update) the file?

 $(document).ready(function (e) {
     $('#upload').on('click', function () {
     var file_data = $('#file').prop('files')[0];
     var form_data = new FormData();
     form_data.append('file', file_data);
     $.ajax({
             url: 'https://myurl/api/images/upload_form/avatar', // point to server-side controller method
             dataType: 'text', // what to expect back from the server
             cache: false,
             contentType: false,
             processData: false,
             data: form_data,
             type: 'post',
             success: function (response) {
                 $('#msg').html(response); // display success response from the server
                 },
             error: function (response) {
                 $('#msg').html(response); // display error response from the server
                 }
           });
     });
});

user_id=1 << I need to add this key and value to the post url, but how?

Any help will be appreciate.

Thanks

DAVE
  • 111
  • 11
  • For #1: https://stackoverflow.com/questions/44283986/how-to-upload-image-through-jquery. For #2 the request would be roughly the same as #1, but exactly how you format it, and the type of request, would depend on the API you're calling. – Rory McCrossan May 29 '19 at 14:33
  • Whose API are you using? "Web-API" is a generic term – j08691 May 29 '19 at 14:34
  • @Rory McCrossan I have tried this code for days. I can only return the response the with last_id but the user_id was undefined! – DAVE May 29 '19 at 15:53

1 Answers1

0

For those new guys who still struggling like I was:

1. How can I attach the image file and post it through Web-API with jQuery?

Uploading the image but response: { 'user_id' of undefined } ?

Before you post the your request, you have to grab parameters form the URL.

var urlParams = new URLSearchParams(window.location.search); // current URL 

console.log(urlParams.get('user_id')); // return token id or user id

and all you have to do is put this:

...
var user_data = urlParams.get('user_id'); // or token
form_data.append('user_id', user_data);
$.ajax({
        url: 'https://myurl/api/images/upload_form/avatar', 
        dataType: 'text', 
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        ...

2. And How can I re-upload(update) the file?

Just upload another file!

Might not be the right way to do that, but works!

DAVE
  • 111
  • 11