1.vue中
<Upload
class="writeResumeHeadImg"
:show-upload-list="false"
:before-upload="handleUpload"
action="//jsonplaceholder.typicode.com/posts/">
<img class="jm-upload-img" :class="imgClass" :src="imgUrl" />
</Upload>
js
handleUpload(file) {
// 需要傳給後臺的file文件
this.file = file;
// FileReader api 爲用戶提供了方法去讀取一個文件或者一個二進制大對象,
// 並且提供了事件模型讓用戶可以操作讀取後的結果
const reader = new FileReader();
// readAsDataURL:讀取爲base64格式
reader.readAsDataURL(file);
// onload 在文件讀取成功時觸發
reader.onload = () => {
const ImgBase64 = reader.result;
// 實現預覽,實際是拿到圖片的base64數據去掛在到圖片的src上
this.imgUrl = ImgBase64;
};
this.postImage();
return false;
},
postImage() {
var file = this.file;
let data = new FormData();
data.append("file", file, file.name); //很重要 data.append("file", file);不成功
data.append("data", 112);
console.log(data.get("file"));
this.axios.post("resumes/file", data, {
headers: { "content-type": "multipart/form-data" }
});
}
2.node中,upload爲node中的新建的存圖片的文件夾
//上傳接口
router.post('/file',
multer({
//設置文件存儲路徑
dest: 'upload' //upload文件如果不存在則會自己創建一個。
}).single('file'), function (req, res, next) {
if (req.file.length === 0) { //判斷一下文件是否存在,也可以在前端代碼中進行判斷。
res.json({
status: "1",
msg: "上傳失敗" + err
});
} else {
let file = req.file;
let fileInfo = {};
console.log(file);
fs.renameSync('./upload/' + file.filename, './upload/' + file.originalname);//這裏修改文件名字,比較隨意。
// 獲取文件信息
fileInfo.mimetype = file.mimetype;
fileInfo.originalname = file.originalname;
fileInfo.size = file.size;
fileInfo.path = file.path;
// 設置響應類型及編碼
res.set({
'content-type': 'application/json; charset=utf-8'
});
res.json({
status: "0",
msg: "上傳成功"
});
}
}
);