我正在尝试将图片上传到服务器,我首先尝试使用此方法:Trouble to upload images with FileTransfer 但是我找不到问题。
现在我在服务器上使用另一个功能,该功能与iOS应用程序配合使用,但不适用于android离子功能。
服务器确实收到HTTP POST请求,但我找不到如何发送图像。
以下是应用程序代码:
takePhoto(value){
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.PNG,
mediaType: this.camera.MediaType.PICTURE,
correctOrientation : true,
allowEdit:true,
targetWidth: 500,
targetHeight: 500,
sourceType : value,
saveToPhotoAlbum: true
}
this.camera.getPicture(options).then((imageData) => {
let base64Image = 'data:image/jpg;base64,' + imageData;
console.log(base64Image)
const fileTransfer: FileTransferObject = this.transfer.create();
let formData = new FormData();
formData.append('photo', imageData);
var headers = new Headers();
//headers.append('Content-Type', 'multipart/form-data; boundary=uwhQ9Ho7y873Ha');
//headers.append('Content-Disposition', 'form-data');
//let options = new RequestOptions({ headers: headers });
var options : FileUploadOptions = {
fileKey: "photo",
chunkedMode: false,
mimeType: "multipart/form-data",
};
//tried this way
this.http.post("http://51.255.174.99:90/add/photo/" + this.user._id,
formData, options).subscribe(data => {
console.log("data = " + data);
});
//and this way
fileTransfer.upload(imageData,"http://XX.XXX.XXX.XX:90/add/photo/" + this.user._id, options).then((data) => {
console.log("data = " + data);
this.presentToasti("It worked !");
}, (err) => {
console.log("upload failed");
})
}, (err) => {
this.presentToasti(err);
});
}
presentToasti(msg) {
let toast = this.toastCtrl.create({
message: msg,
duration: 3000,
position: 'bottom'
});
toast.onDidDismiss(() => {
console.log('Dismissed toast');
});
toast.present();
}
这里是服务器代码(我不会触摸它,它在iOS上运行应该没有任何问题):
exports.addphoto = function (req, res) {
var phone = require('phone');
var wine={};
var ObjectID = require('mongodb').ObjectID;
var form = new formidable.IncomingForm();
console.log(form);
var size=0;
var retour={};
form.parse(req, function(err, fields, files) {
if(typeof files['photo'] !== "undefined" && files['photo']!= ""){
size = files['photo']['size'];
}else{
size=0;
}
console.log('files:'+JSON.stringify(files['photo']['size']));
});
console.log(size);
form.on('end', function (fields, files) {
if(typeof this.openedFiles[0]!=="undefined"){
var temp_path = this.openedFiles[0].path;
console.log("temp path : "+temp_path);
if(size>0){
console.log('bonjour');
var file_name = req.params.id+".png";
var new_location = "/var/xxxxx/public/upload/photoprofil/";
im.resize({
srcData: fs.readFileSync(temp_path, 'binary'),
dstPath: temp_path,
width: 500
},function(err, stdout, stderr){
if (err) throw err
fs.copy(temp_path, new_location + file_name, function (err) {
if (err) {
console.log("erreur : photo de profil non ajoutee");
retour['photo']='erreur';
res.send(retour);
} else {
console.log("photo de profil ajoutee");
retour['photo']='';
res.send(retour);
}
});
});
}
else{
retour['photo']='pas de photo';
res.send(retour);
}
}else{
res.send(retour);
}
});
}
带有fileTransfer.upload方法的Console.log:
{ 'content-type': 'multipart/form-data; boundary=+++++',
'user-agent': 'Dalvik/2.1.0 (Linux; U; Android 8.0.0; ONEPLUS A5010 Build/OPR1.170623.032)',
host: 'XX.XXX.XXX.XX:90',
connection: 'Keep-Alive',
'accept-encoding': 'gzip',
'content-length': '0' }
{}
form {"domain":null,"_events{},"_eventsCount":0,"error":null,"ended":false,"maxFields":1000,"maxFieldsSize":2097152,"keepExtensions":false,"uploadDir":"/tmp","encoding":"utf8","headers":null,"type":null,"hash":false,"multiples":false,"bytesReceived":null,"bytesExpected":null,"_parser":null,"_flushing":0,"_fieldsSize":0,"openedFiles":[]}
{}
files:0
POST /add/photo/5a1fd1a89a6f09412b6a74d7 200 23.479 ms - 2
使用this.http.post方法的Console.log:
GET /upload/photoprofil/5a1fd1a89a6f09412b6a74d7.jpg 304 1.075 ms - -
{ host: 'XX.XXX.XXX.XX:90',
connection: 'keep-alive',
'content-length': '345852',
accept: 'application/json, text/plain, */*',
origin: 'file://',
'user-agent': 'Mozilla/5.0 (Linux; Android 8.0.0; ONEPLUS A5010 Build/OPR1.170623.032; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 Mobile Safari/537.36',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryaAt6z22k3aTPNeCt',
'accept-encoding': 'gzip, deflate',
'accept-language': 'fr-FR,en-US;q=0.9',
'x-requested-with': 'io.ionic.starter'
{}
form {"domain":null,"_events{},"_eventsCount":0,"error":null,"ended":false,"maxFields":1000,"maxFieldsSize":2097152,"keepExtensions":false,"uploadDir":"/tmp","encoding":"utf-8","headers":null,"type":null,"hash":false,"multiples":false,"bytesReceived":null,"bytesExpected":null,"_parser":null,"_flushing":0,"_fieldsSize":0,"openedFiles":[]}
{}
files:0
POST /add/photo/5a1fd1a89a6f09412b6a74d7 200 333.681 ms - 2
正如您所看到的,使用this.http.post方法,内容长度看起来像上传的图像。 但是console.log('files'+ JSON.stringify(files ['photo'] ['size']));不会像我们使用iOS应用程序那样显示文件的大小。
对于缩进样式很抱歉,我找不到Stackoverflow处理代码的方式。
答案 0 :(得分:0)
destinationType: this.camera.DestinationType.FILE_URI,
设置相机时使用文件uri而不是数据网址。然后使用以下方法。
fileTransfer.upload(imageData,"http://XX.XXX.XXX.XX:90/add/photo/" + this.user._id, options).then((data) => {
console.log("data = " + data);
this.presentToasti("It worked !");
}, (err) => {
console.log("upload failed");
})
}, (err) => {
this.presentToasti(err);
});