[英]Why is my image file being converted to a string?
編輯,原來的問題已解決,為什么文件轉換為字符串。 該代碼已被編輯以反映這些更正。 API處理程序現在將對象輸出為數據類型,並將緩沖區輸出為request.payload.file的值。
我正在使用Aurelia制作單頁應用程序。 有一個HTML表單可以接受兩個輸入字段,一個輸入域用於文件,一個輸入域用於文本。 這些字段綁定到關聯的TypeScript視圖模型中的變量(selecetdImage和title)。 在viewmodel中,它們用作函數的參數,該函數將其附加到formData並將帶有formData的http發布請求發送到Node / js Hapi框架API處理程序。
當我在Aurelia應用程序中console.log(typeof(selectedImage)時,它聲明對象,但是當我在處理程序中控制台log typeOf(selecetdImage)時,我得到了String。我猜測這就是為什么我的函數不起作用並且給出500條錯誤消息
處理程序本身可以工作。 我在基於MVC服務器的Web應用程序中使用了它。 在這種情況下,HTML表單觸發了發布請求,並且MVC處理程序成功接收了文件,將其寫入local / temp.img並將其上傳到cloudinary。 但是在API版本中,我如上所述自己在其中組裝了表單數據,該文件未寫入local / temp.img,並且cloudinary上傳失敗。
編輯。 我將viewmodel變量更改為title = null; files = null;
我將formData追加函數更改為:
formData.append('file',File,files [0]);
按照這里的例子。 現在,下面的代碼已被修改以匹配此更新。
現在,當我在API處理程序中控制台記錄文件的值時,輸出為:
<Buffer ff d8 ff e0 00 10.......
我不確定該如何處理。 我假設它是八進制的圖像二進制數據? 如果是這樣,有人知道如何在節點中將其寫為映像嗎? 有效負載不再是字符串類型,現在是對象類型。
<form submit.delegate="uploadPhoto()" enctype="multipart/form-data">
<div class="two fields">
<div class="field">
<label>File</label>
<input type="file" name="file" accept="image/png, image/jpeg" files.bind="files">
</div>
<div class="field">
<label>Title</label> <input value.bind="title">
</div>
</div>
<button type="submit"> Upload </button>
</form>
//photoUpload.ts// (view model associated with above html
@inject(POIService)
export class PhotoForm {
@bindable
photos: Photo[];
title = null;
files = null;
constructor (private poi: POIService) {}
uploadPhoto() {
const result = this.poi.uploadPhoto(this.title, this.files);
console.log(this.title);
console.log(result);
}
//POIService (where contains injected function to create HTTP request
async uploadPhoto(title: string, files){
console.log("now uploading photo for: " + this.currentLocation)
let formData = new FormData();
formData.append("title", title);
formData.append("location", this.currentLocation); //don't worry about this variable, it's set by another function every time a page is viewed
formData.append("file", files[0]);
const response = await this.httpClient.post('/api/locations/' + this.currentLocation + '/photos', formData);
console.log(response);
}
//API Handler (accepts HTTP request, writes the image to a local folder, the uploads to cloudinary and returns the url and photo_id which are stored in a Mongod document
create: {
auth: false,
handler: async function(request, h) {
const photo = request.payload.file;
await writeFile('./public/temp.img', photo);
const result = await cloudinary.v2.uploader.upload('./public/temp.img', function(error, result) {
console.log(result)
});
const newPhoto = new Photo({
title: request.payload.title,
url: result.url,
public_id: result.public_id,
location: request.params.name
})
await newPhoto.save();
return newPhoto;
}
},
它是一個很長的字符串,在前15個左右的字符中包含“ data:b64”嗎? 如果是這樣,則意味着它是base64數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.