【发布时间】:2020-09-29 18:13:25
【问题描述】:
我有一个要求,我需要从手机库/相机中选择图像并通过 POST api 上传到服务器。我能够从库中加载图像,但在使用 post 请求发送图像时出错
我的 HTML 代码:
<p (click)="selectImage()">Add an attachment</p></ion-item>
我的 .ts 文件:
import { HTTP } from "@ionic-native/http/ngx";
async selectImage() {
const actionSheet = await this.actionSheetController.create({
header: 'select image',
buttons: [{
text: 'Load from library',
handler: () => {
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
});
await actionSheet.present();
}
takePicture(sourceType: PictureSourceType) {
var options: CameraOptions = {
quality: 100,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
this.camera.getPicture(options).then(imagePath => {
if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
this.file.resolveLocalFilesystemUrl(imagePath).then((entry: FileEntry) => {
entry.file(file => {
console.log(file);
this.readFile(file);
});
});
}
});
}
readFile(file: any) {
const reader = new FileReader();
reader.onloadend = () => {
const formData = new FormData();
const imgBlob = new Blob([reader.result], {
type: file.type
});
formData.append('file', imgBlob, file.name);
this.uploadImageData(formData)
};
reader.readAsDataURL(file);
}
async uploadImageData(formData) {
let feedbackData = {
attachment: formData,
feedback: 'test text'
}
this.http.post('http://abctest.rapidesk.in/api/feedback/', feedbackData, { 'Content-Type': 'application/json', 'Authorization': "Token" + " " + this.authToken })
.then(data => {
console.log(data);
}).catch(err => {
console.log(err)
})
}
【问题讨论】:
-
请尝试关注http.post...:
,{data:formData}, -
@YunusEmreBAKAÇ 试过了,但似乎没有用,仍然出现同样的错误
-
您发送的不是 JSON。不要对你的 API 撒谎
-
我已更新我的问题并将对象正确传递给我的 api。那里的服务器需要文件
标签: javascript angular ionic-framework ionic4 angular8