我在前端使用multipart/form-data
,后端使用multer
来处理我正在构建的网站上的图像上传。
我遇到了一个问题,我想在提交表单之前在屏幕上显示图像,但我无法,因为缓冲区直到它经过multer(我认为)后才生成
这是传递到后端之前的FormData负载
lastModified: 1608334888059
lastModifiedDate: Fri Dec 18 2020 18:41:28 GMT-0500 (Eastern Standard Time) {}
name: "photomode_18122020_184125.png"
size: 4776395
type: "image/png"
webkitRelativePath: ""
[[Prototype]]: File
下面是后台的FormData负载
buffer:Buffer(4776395) [137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 10, 0, 0, 0, 4, 56, 8, 6, 0, 0, 0, 197, 66, 133, 69, 0, 0, 0, 19, 116, 69, 88, 116, 84, 105, 116, 108, 101, 0, 73, 109, 97, 103, 101, 83, 97, 118, 101, 114, 80, 78, 71, 215, 75, 83, 237, 0, 0, 0, 10, 116, 69, 88, 116, 85, 115, 101, 114, 68, 97, 116, 97, 0, 48, 56, 179, 7, 148, 0, 0, 32, 0, 73, 68, 65, 84, 120, 156, 76, 188, 89, 175, …]
encoding:'7bit'
fieldname:'files'
mimetype:'image/png'
originalname:'photomode_18122020_184125.png'
size:4776395
前端代码... html ...
<form enctype="multipart/form-data">
<input type="file" :name="uploadFieldName" :disabled="isSaving" @change="filesChange($event.target.name, $event.target.files); fileCount = $event.target.files.length" accept="image/*" class="input-file">
</form>
... script tag now ...
formData.append("photo", fieldName);
for(let i =0; i < fileList.length; i++) {
formData.append("files", fileList[i]);
}
// API call for photo
// The form data at this point does not have the buffer for some reason :/
this.save(formData);
后端代码
import multer from "multer"
const upload = multer();
// This is where the buffer is available
app.post("/photo", upload.any(), function(req, res, next) { photoService.create(req, res) })
缓冲区从哪里来?我如何在发送请求之前访问缓冲区,我想让我的用户在他们按下提交之前在屏幕上预览图像。
你可以使用一个名为FileReader
的类,这将允许你在将图像上传到后端之前预览图像,这里有一个例子
<div id="preview"></div>
<input type="file" id="uploader">
$("#uploader").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$("#preview").attr("src", e.target.result);
};
reader.readAsDataURL(this.files[0]);
}
});