I am utilizing multipart/form-data on the front end and multer on the back end to handle image uploads on a website I am building.
I am running in to an issue where I want to have the image display on the screen before submission of the form but I am unable to because the buffer is not generated until after it goes through multer (I think)
Here is the FormData payload BEFORE it is passed to the backend
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
Here is the FormData payload on the backend
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
Frontend code
... 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);
Backend code
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) })
Where is the buffer coming from? And how can I access the buffer before I send the request, I want to allow my users to preview the image on the screen before they press submit.
You could use a class called FileReader this will allow you to preview the image before upload it to the backend and here is an example
<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]);
}
});