Form Post with image Upload

Hi everyone,
I am trying to upload and save data from a phonegap app with framework7 to Wordpress.
I have created the javascript request to sent the info.
This is the code I have:

app.request({
    url: 'http://domain.com/wordpress/wp-json/test_post/v1/post_media',
    method: "POST",
    data: formData,
    cache: false,
    dataType: "application/json",
    mimeType: "multipart/form-data",
    processData: true,
    beforeSend: function ( xhr ) {
        console.log( "BEFORE SEND" );
        app.dialog.alert(JSON.stringify(xhr), "BEFORE SEND");
        xhr.setRequestHeader( 'Authorization', 'Basic '+username+':'+password );
    },
    success: function( data ) {
        app.dialog.alert(JSON.stringify(data), "SUCCESS");
        console.log( "SUCCESS" );
        console.log( data );
    },
    error: function( error ) {
        console.log( "ERROR" );
        app.dialog.alert(JSON.stringify(error), "ERROR");
        console.log( error );
    }
});

And this is the Wordpress rest_route

add_action( 'rest_api_init', function(){
  register_rest_route( 'test_post/v1', '/post_media', array(
   'methods' => 'POST',
   'callback' => 'my_rest_add_from_app',
  ));
});

function my_rest_add_from_app($data) {
    return $data;
}

It alerts everything (BEFORE SEND and SUCCESS) but the content on SUCESS is {}
Where is the data that I passed?

What am I missing…

Hi i use axios to make request, here is how i upload a file. Its call from my util js and returns a promise.

  uploadFile: (opts, headers) => new Promise((resolve, reject) => {
    const token = vue.cookie.get('token')
    var instance = axios.create({
      baseURL: !store.getters.debug ? 'https://PROD-URL' : 'https://DEV-URL',
      timeout: 300000,
      headers: {
        'Content-Type': 'text/raw',
        'Authorization': 'Bearer ' + token.headers,
        'Bucket-Id': headers.bucketId
      }
    })
    instance.interceptors.request.use(function (config) {
      store.commit('TOGGLE_SHOW_UPLOAD_PROGRESS')
      return config
    })
    instance.interceptors.response.use(function (response) {
      store.commit('TOGGLE_SHOW_UPLOAD_PROGRESS')
      return response
    }, function (error) {
      store.commit('TOGGLE_SHOW_UPLOAD_PROGRESS')
      return error
    })
    instance({
      method: 'post',
      url: 'UploadFile',
      data: opts,
      onUploadProgress: (progressEvent) => {
        const { loaded, total } = progressEvent
        let progress = parseInt(Math.round((loaded * 100) / total))
        store.dispatch('setUploadProgress', progress)
      }
    }
    ).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  }),

and to call it:

let data = new FormData()
  // this.file is my file-browser file, i use vue
  data.append('file', this.file)
   let params = {
     bucketId: this.selectedRepo.id
   }
   Util.uploadFile(data, params).then(res => {
     let result = res.data.data[0]
       if (result.Result === 200) {
         vm.saveFile(result)
       }
     }).catch(err => {
       console.log(err)
     })

Maybe it helps you.
You say that success alert, data is {}, but did your file upload?

2 Likes

It should be contentType instead of mimeType

contentType: "multipart/form-data",

Same answer from server “{}”

But did the file upload correctly? if it does, then is a server issue the empty data.

Try processData: false

iPhone X image uploads for my webapp only worked with set to false

Ok I managed to put everything working. The problem now is that it work on my iMac Chrome but doesn’t work on my devices using Phonegap Developer App.
It executes the code inside the error Callback.

Why?

The error output from console.log( error ) would be super helpful

XMLHttpRequest
weinreNetworkRequest: NetworkRequest
id: 193
method: “POST”
stackTrace: Array[0]
length: 0
proto: —
url: “https://www.diecast-collections.com/api/userplus/add_post?key=5ae1561&title=Tegdhsh&content=Te…
xhr: XMLHttpRequest
weinreNetworkRequest: NetworkRequest
__weinre__id: 192
__weinre_method: “POST”
__weinre_url: “https://www.diecast-collections.com/api/userplus/add_post?key=5ae1561&title=Tegdhsh&content=Te…
requestParameters: Object
async: true
beforeSend: function ( xhr ) {
cache: false
contentType: “multipart/form-data”
crossDomain: true
data: Object
dataType: “application/json”
error: function ( error ) {
arguments: null
caller: null
length: 1
name: “error”
prototype: error
constructor: function ( error ) {
proto: —
proto: —
headers: Object
method: “POST”
password: “”
processData: true
statusCode: Object
success: function ( data ) {
timeout: 0
url: “https://www.diecast-collections.com/api/userplus/add_post?key=5ae1561&title=Tegdhsh&content=Te…
user: “”
xhrFields: Object
proto: —
requestUrl: “https://www.diecast-collections.com/api/userplus/add_post?key=5ae1561&title=Tegdhsh&content=Te…
proto: —
proto: —
__weinre__id: 192
__weinre_method: “POST”
__weinre_url: “https://www.diecast-collections.com/api/userplus/add_post?key=5ae1561&title=Tegdhsh&content=Te…
requestParameters: Object
async: true
beforeSend: function ( xhr ) {
cache: false
contentType: “multipart/form-data”
crossDomain: true
data: Object
dataType: “application/json”
error: function ( error ) {
headers: Object
method: “POST”
password: “”
processData: true
statusCode: Object
success: function ( data ) {
timeout: 0
url: “https://www.diecast-collections.com/api/userplus/add_post?key=5ae1561&title=Tegdhsh&content=Te…
user: “”
xhrFields: Object
proto: —
requestUrl: “https://www.diecast-collections.com/api/userplus/add_post?key=5ae1561&title=Tegdhsh&content=Te…
proto: —

Any Ideas??? I don’t know what else to do. I’ve also tried with app.request.postJSON and nothing.

Here the XMLHttpRequest:

XMLHttpRequest
    __weinreNetworkRequest__: NetworkRequest
    __weinre__id: 207
    __weinre_method: "POST"
    __weinre_url: "https://www.domain.com/api/userplus/add_post"
    requestParameters: Object
        async: true
        beforeSend: function ( xhr ) {
        cache: false
        contentType: "multipart/form-data"
        crossDomain: true
        data: Object
        dataType: "application/json"
        error: function ( error ) {
        headers: Object
        method: "POST"
        password: ""
        processData: true
        statusCode: Object
        success: function ( data ) {
        timeout: 0
        url: "https://www.domain.com/api/userplus/add_post"
        user: ""
        xhrFields: Object
        __proto__: —
        requestUrl: "https://www.domain.com/api/userplus/add_post"
        __proto__: —

can you make a jsfiddle with the error?

Sorry, the url to send must have a key that is personal.

After re-login the user everything is working. Sorry never thought of that!!!

1 Like

updates on the upload.

The most awkward thing is that it works on iOS, and android 4.4.4 and 8.0 but it doesn’t work on Samsung Galaxy S6 with Android 7.0.
Why?

Please is there any issues with android 7.0 or Samsung phones?

Using: Phonegap 7.1.1, Cordova 8.0.0, Framework7 and jQuery (getting rid of jQuery).