我整天都在除錯這個,終于沒有谷歌搜索選項了。
我有一個 Vue3 前端,它接收影像并且應該將所述影像發送到后端。我已經驗證了影像實際上正在被發送,但是無論前端/網路說正在發送什么,Multer 中的檔案物件每次都顯示未定義。
這是我的代碼
前端
<template>
<div class="flex justify-center">
<div class="mb-3 w-96">
<label for="formFile" class="form-label inline-block mb-2 text-gray-700"
>Upload a new profile picture</label
>
<input
class="form-control block w-full px-3 py-1.5 text-base font-normal text-gray-700 bg-white bg-clip-padding border border-solid border-gray-300 rounded transition ease-in-out m-0 focus:text-gray-700 focus:bg-white focus:border-blue-600 focus:outline-none"
type="file"
@change="onSelect"
id="formFile"
/>
<span class="message"> {{ message }} </span>
</div>
</div>
</template>
<script>
import axios from "redaxios";
export default {
name: "FileUpload",
props: {
user: Array | Object,
},
created() {},
data() {
return {
file: "",
message: "",
};
},
methods: {
onSelect(e) {
this.file = e.target.files[0] || e.dataTransfer.files;
if (this.file.length) return;
const formData = new FormData();
console.log(this.file);
formData.append("id", this.user.id);
formData.append("file", this.file);
//formData.set("enctype", "multipart/form-data");
console.log(formData);
try {
axios
.post("http://localhost:3669/uploadPhoto", formData)
.then((res) => {
this.message = "Uploaded successfully!";
});
} catch (err) {
console.log(err);
this.message = "Something went wrong uploading your photo!";
}
},
},
};
</script>
后端
const fileFilter = (req: express.Request, file: File, cb) => {
const allowedTypes = /jpeg|jpg|png|gif/;
const extname = allowedTypes.test(path.extname(file.name).toLowerCase());
const mimetype = allowedTypes.test(file.type);
if (!mimetype && extname) {
const error = new Error("Incorrect Filetype");
error.name = "INCORRECT_FILETYPE";
return cb(error, false);
}
cb(null, true);
}
const storage = multer.diskStorage({
destination: function (req, file, cb) {
if (req.body.id) {
cb(null, `./public/photos/${req.body.id}`)
} else {
cb(null, "./public/photos");
}
},
filename: function (req, file: File, cb) {
console.log(req.file);
cb(null, file.name ".png");
},
});
const imageUpload : Multer = multer({
storage,
limits: {
fileSize: 5000000
}
});
app.post('/uploadPhoto', imageUpload.single('file'), async (req: express.Request, res:express.Response) => {
console.log(req.body);
console.log(req.file);
res.json({ message: 'Successfully uploaded file' });
return;
});
出于空間原因,我省略了一些代碼,但由于某種原因,它不起作用。記錄的檔案回傳一個檔案,但后端拒絕查看它。
謝謝
- 扎克
uj5u.com熱心網友回復:
看來您的 Multer DiskStorage 配置是問題的原因。
我的猜測是你有錯誤的檔案路徑,因為./不是你想的那樣。這就是為什么從__dirname(當前腳本的父目錄)決議路徑總是好的原因。
請注意,destination各州的檔案...
如果傳遞了一個字串并且該目錄不存在,Multer 會嘗試遞回地創建它
因此,由于您使用的是函式版本,因此您需要手動創建上傳目錄。
您的filename鉤子中也有錯誤的引數型別。file引數是型別,Express.Multer.File不是File。您不需要設定它,因為它已經由函式簽名定義。
import { resolve } from "path";
import { mkdir } from "fs/promises";
import multer from "multer";
const uploadBase = resolve(__dirname, "./public/photos");
const storage = multer.diskStorage({
destination: async (req, _file, cb) => {
const path = req.body.id ? resolve(uploadBase, req.body.id) : uploadBase;
try {
// create the directory
await mkdir(path, { recursive: true });
cb(null, path);
} catch (err) {
cb(err);
}
},
filename: (_req, file, cb) => {
cb(null, file.originalname); // note the property used
}
});
確保安裝@types/multer為開發依賴項,以便在編輯器中獲得有用的 linting。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/455404.html
標籤:javascript 节点.js 打字稿 表示 穆尔特
下一篇:Express驗證器自定義功能
