序:一般来说,你网上找到资料会在fs.writeFileSync那步骤卡住,博主也找到了原因。
文章为博主原创,原创不易,高抬贵手
运行效果如下图:
先跟着博主来 ,以下是 相关配置
1、下载依赖
cnpm install egg-multipart -S
2、config.default.js 配置
config.multipart = {
mode: 'file'
};
3、路由 router.js
router.get('/imgUpView', controller.home.imgUpView);
router.post('/imgUp', controller.home.imgUp);
4、app/controller/home.js
先引入 ,这两个插件是 egg自带的,不用npm install !!!!!!!!!
const fs = require('fs')
const path = require('path')
方法:
async imgUp(){
const { ctx } = this;
const file = ctx.request.files[0];
const fileinfo = fs.readFileSync(file.filepath);
const name = `CYC_${new Date().getTime()}_${file.filename}`;
const target = path.join(this.config.baseDir, `app/public/upload/${name}`);
try {
await fs.writeFileSync(target, fileinfo);
} catch (error) {
throw error;
} finally {
await fs.unlink(file.filepath, err => {
if (err) {
throw err;
}
console.log('删除缓存文件:' + file.filepath + '成功!');
});
}
debugger
ctx.body = { code: 200, message: '上传成功!', data: target, file };
}
async imgUpView(){
const {ctx}=this;
await ctx.render('imgUpView.html',{});
}
5、app/public/ 新建 文件夹 upload 记住 你不新建到时候 代码跑到fs.writeFileSync 会报错4058
6、app/view/imgUpView.html (新建 imgUpView.html)
<html>
<head>
<title>Hacker News</title>
<script type="text/javascript" src="../../public/jquery-2.1.4.min.js"></script>
</head>
<body>
<a href="javascript:void(0);" id="btn_uploadimg">提交</a>
<input type="file" id="FileUpload"/>
<p id="url"></p>
<script type="text/javascript">
$(()=>{
$("#btn_uploadimg").click(function () {
var fileObj = document.getElementById("FileUpload").files[0]; // js 获取文件对象
if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
alert("请选择图片");
return;
}
var formFile = new FormData();
formFile.append("action", "UploadVMKImagePath");
formFile.append("file", fileObj); //加入文件对象
//第一种 XMLHttpRequest 对象
//var xhr = new XMLHttpRequest();
//xhr.open("post", "/Admin/Ajax/VMKHandler.ashx", true);
//xhr.onload = function () {
// alert("上传完成!");
//};
//xhr.send(formFile);
//第二种 ajax 提交
var data = formFile;
$.ajax({
url: "/imgUp",
data: data,
type: "Post",
dataType: "json",
cache: false,//上传文件无需缓存
processData: false,//用于对data参数进行序列化处理 这里必须false
contentType: false, //必须
success: function (result) {
$("#url").html('服务器存储路径为:'+result.data)
},
})
})
})
</script>
</body>
</html>
到这里就可以了 访问地址 http://localhost:7001/imgUpView
上传个 jpg的文件 你的文件会 在upload 文件夹里
文章为博主原创,原创不易,高抬贵手