我有一个需要从手机库/相机中选择图像并通过POST API上传到服务器的要求。我能够从库中加载图像,但是在使用发布请求发送图像时出现错误]
我的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://kairav.rapidesk.in/api/feedback/', feedbackData, { 'Content-Type': 'application/json', 'Authorization': "Token" + " " + this.authToken })
.then(data => {
console.log(data);
}).catch(err => {
console.log(err)
})
}
我有一个需要从手机库/相机中选择图像并通过POST API上传到服务器的要求。我能够从库中加载图像,但是在发送...
您应该使用FormData,并且在html中使用input type =“ file”