Can't upload base64 image using cordova-plugin-file-transfer

一个人想着一个人 提交于 2019-12-10 16:46:19

问题


I'm trying to upload my image in base64 to my server using cordova-plugin-file-transfer and until now it's not working. My code is like this:

photoBase64 = photoBase64.replace('data:image/png;base64,', '');

var url = "http://MYURL.com/path";

var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = "photoName.png";
options.mimeType = "image/png";

var ft = new FileTransfer();

ft.upload(photoBase64, 
          encodeURI(url), 

          function(result) {

                console.log("Code = " + result.responseCode);
                console.log("Response = " + result.response);
                console.log("Sent = " + result.bytesSent);
                resolve("OK");
          }, 

          function(error) {

                alert("An error has occurred: Code = " + error.code);
                console.error("ERROR", error);
                console.log("upload error source " + error.source);
                console.log("upload error target " + error.target);
                reject("ERROR");
          }, 

          options);

And I'm getting the following error with this code:

How can I upload image base64 using cordova-plugin-file-transfer?

Thanks in advance!


回答1:


I'm a year late to the party but I just came upon the answer through trial and error:

You must leave "data:image/png;base64," in the string. I assume without that format it's not a valid url.

specifically in your case, delete this line:

photoBase64 = photoBase64.replace('data:image/png;base64,', '');

It was really that simple for me to get my upload working.




回答2:


The file transfer plugin doesn't take Base64 strings. You have to use the location of the file (file:://android/etc). More info about the File plugin to get the file (this plugin is automatically installed with the filetransfer plugin) is here:

https://github.com/apache/cordova-plugin-file

If you would really want to just use the base64 string, you would have to use $http.post and write a api on the receiving side to recreate the file



来源:https://stackoverflow.com/questions/37063410/cant-upload-base64-image-using-cordova-plugin-file-transfer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!