NodeJS 如何使用Multer将文件上传到vuejs中前端定义的特定目录中

aurhwmvo  于 2023-01-20  发布在  Node.js
关注(0)|答案(1)|浏览(123)

我想使用Multer在我的NodeJs应用程序中由vuejs中的前端定义的特定目录中上传一个文件。
这是我第一次申请multer
后端代码为:

...
const app = express();

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        //req.body.idUser is undefined here
        let destinationPath = path.join("upload_file", req.body.idUser);
        if (!fs.existsSync(destinationPath)) {
            fs.mkdirSync(destinationPath);
        }
        cb(null, destinationPath);
    },
    filename: (req, file, cb) => {
        let newFileName = Date.now() + path.extname(file.originalname);
        cb(null, newFileName);
    },
});

const upload = multer({ storage });

app.post(
    "/file/add",
    upload.fields([{ name: "newfile" }, { name: "idUser" }]),
    (req, res) => {
        res.json({
            response: "file uploaded",
        });
    },
);
...

前端代码是:

...
async sendDocument(event){
    const file = event.target.files[0]
    const form = new FormData()
    form.append("newfile", file, file.name)
    form.append("idUser", this.getIdUser)
    const opts =
    {
        method: "POST",
        body: form,
    }
    const url = "http://localhost:3000/file/add";
    try{
        await fetch(url, opts)
        .then(function (response) {
            return response.json();
        })
        .then(function (res) {
            console.log(res)
        });
    }catch(err){
        console.log(err)
    }
},
...

我尝试使用console.log逐步进行调试,以检查storage中未定义req.body.idUser的原因,我需要它来完成destinationPath
如果用静态值(如"toto")替换req.body.idUser,则一切正常
在前面,this.getIdUser工作正常,req.body.idUserapp.post中工作正常
谢谢你的帮忙

c90pui9n

c90pui9n1#

请先尝试将ID追加到表单:

const form = new FormData()
form.append("idUser", this.getIdUser)
form.append("newfile", file, file.name)

相关问题