'How to pass a file to server and then send it back to client?
I'm currently working with pdf files in ReactJS and modifying them in my server side. The problem is, i don't know how to pass my file data to the server side and then send it back.
this is how i get my file :
<div className={"input-file"}>
<input className="file-upload-field" type="file" accept="application/pdf" onChange={onFileChange}/>
</div>
And then i have
async function modifyPdf(doc, pageNumber) {
let chemin = [
`/testun/${doc}`
];
await Promise.all(chemin.map(url => {
fetch(url)
.then(checkStatus) // check the response of our APIs
.then(parseJSON) // parse it to Json
.catch(error => console.log('There was a problem!', error))
}
))
.then(response => {
newdoc = response[0];
});
return doc//newdoc;
}
the problem is that if i want to send an url it would be local, so node wouldnt be able to retrieve the resource (i think? because it's a blob url), and is it possible to pass the arrayBuffer ? Because when i do so, it passes [object arrayBuffer] as a parameter to my route so i don't really know if there is a better option.
Thank you!
Solution 1:[1]
You can upload your files using multer. You can access the uploaded file from the destination folder on the server or local
const express = require("express");
const multer = require("multer");
const upload = multer({ dest: "uploads/" });
const app = express();
app.post("/upload", upload.single("productImage"), function (req, res, next) {
var filename = req.file.filename;
res.redirect("/public/uploads/" + filename);
});
upload.single('productImage') refers to the the input element name and you can get the file name on the backend with req.file.filename
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type='file' name="productImage" required/>
<button type="submit">Submit</button>
</form>
After that you can access the file on the front-end http://localhost:3000/uploads/<filename>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |