我使用Cordova ImagePicker插件从手机图库中挑选图片。它返回图像文件URI。如何根据URI路径将该图像发送到服务器?
pickImage() {
ImagePicker.getPictures({maximumImagesCount: 1}).then(
results => {
results.map(file_uri => {
console.log('GOT FILE URI: ' + file_uri);
// SEND FILE TO SERVER
});
}, err => {
}
);
}
尝试但失败了:
答案 0 :(得分:0)
Base64插件似乎运行正常。它从图像URI路径获取base64字符串,然后可以将其发布到服务器。
示例客户端代码 - JavaScript(ES6):
pickImage() {
ImagePicker.getPictures({maximumImagesCount: 1}).then(
results => {
results.map(file_uri => {
console.log('GOT FILE URI: ' + file_uri);
window.plugins.Base64.encodeFile(file_uri, base64 => {
// POST base64 string to server;
}, error => {
console.error(error);
});
});
}, error => {
console.error(error);
}
);
}
POST处理程序中的示例服务器代码 - Python:
import base64
...
def post(self, filename):
b64string = self.request.body.decode()
b64data = b64string.split(',')[1]
binary = base64.b64decode(b64data)
with open('/path/to/images/' + filename, 'wb') as f:
f.write(binary)
额外 - 如果您需要获取只需要使用File API的二进制文件,您可以创建一个类似Blob(source):
base64toBlob(base64string) {
var byteString = atob(base64string.split(',')[1]);
var mimeString = base64string.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var bb = new Blob([ab], {type: 'image/jpeg'}); // your mime type here
return bb;
}
答案 1 :(得分:0)
你可以简单地使用outputType:1
let options = {
maximumImagesCount: 8,
quality: 100,
outputType: 1
}
ImagePicker.getPictures(options).then((results) => {
for (var i = 0; i < results.length; i++) {
this.uploadImage(results[i]);
}
}, (err) => {
console.log(JSON.stringify(err));
});