I'm having a weird issue I can't quite tease apart. My scenario is that I capture from the camera an image and display it on the web page for someone to preview. If they like it, then they hit upload, and it passes it to the backend to save.
Here's the stack - node on both sides:
// Need to convert the dataURL in the canvas element to a File object for uploading
function dataURLtoFile(dataUrl: string, fileName: string): File {
var arr = dataUrl.split(",");
var first_arr = arr[0]
var match_arr = first_arr?.match(/:(.*?);/);
var mime = 'image/png'
if ((match_arr) && (match_arr?.length > 0)) {
mime = match_arr[1];
}
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], fileName, { type: mime });
}
// Cut out some elements to make it cleaner
function submitInfo() {
let formData = new FormData();
const imageDataUrl = (document?.getElementById("canvas_image") as HTMLCanvasElement).toDataURL();
const objectPicture = dataURLtoFile(imageDataUrl, uuid());
formData.append('objectPicture', objectPicture);
axios.post("/api/upload", formData);
}
app.post("/api/upload", async (req, res) => {
let form = new formidable.IncomingForm();
var metadataFile = null;
var objectPicture = null;
await form.parse(req, function (err, fields, files) {
// The name for our upload includes a prefix we can use to identify our files later
const uploadName = [uuid() + "." + mime.extension(files.objectPicture.mimetype),
].join("|");
var objectPicture = new File(
fs.readFileSync(files.objectPicture.filepath, 'utf8'),
uploadName,
{
type: files.objectPicture.mimetype,
}
);
});
});
So not much there - but when i look at the file, vs the original, it's all just digits (vs. what I assume is proper encoding). What did I get wrong?
Edit: Updated readFileSync with 'utf8' and no change :( Also, looked at the temp file on disk that formidable saved, and it looks fine. So it's something in my code reading it back in that seems to be messing it up!