eggjs 上传文件图文

序:一般来说,你网上找到资料会在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  文件夹里

文章为博主原创,原创不易,高抬贵手

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雪狼之夜

打个赏,让博主知道博文没白写

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值