nodeJs实现文件上传

<el-upload
 :on-change="handleChansge"
 :on-remove="handleRemove"
 :on-exceed="handleExceed"
 :before-remove="beforeRemove"
 :http-request="upload"
 :auto-upload="false"
 :limit="1"
 :file-list="fileList"
 action="#"
accept=".jpg,.png,.pdf,.doc,.docx,.JPG,.PNG,.PDF,.DOC,.DOCX"
 multiple>
<el-button size="small" type="primary">上传简历</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png/pdf/doc/docx文件,且不超过5MB</div>
</el-upload>
data() {
	return {
		fileList: [],
	}
}

    handleChansge(file) {
      if (!/\.(jpg|png|pdf|doc|docx)$/i.test(file.name)) {
        this.$message.error('只能上传jpg/png/pdf/doc/docx文件!')
        this.fileList = []
        return false
      }
      const isLt5M = file.size / 1024 / 1024 <= 5
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
        this.fileList = []
        return false
      }
      this.file = file.raw
      this.upload()
    },
    handleRemove() {
      this.resume_url = ''
    },
    handleExceed() {
      this.$message.warning(`当前只限制选择 1 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}`)
    },
    async upload() {
      // 文件形式的需要用 formData形式
      const formData = new FormData()
      formData.append('file', this.file)
      resumeUpload(formData).then(data => {
        const { errorCode, data: { path }} = data.data
        if (errorCode === 0) {
          this.resume_url = path
          this.$message.success(`上传成功`)
        } else {
          this.filelist = []
          this.file = ''
          this.$message.error(`上传失败`)
        }
      }).catch(err => {
        console.log(err)
        this.filelist = []
        this.file = ''
        this.$message.error(`上传失败`)
      })
    },
import * as fs from 'fs';
import * as path from 'path';
import * as fse from 'fs-extra';
import * as uuidv4 from 'uuid/v4';
  /**
   * @description: 上传简历
   * @param {type}
   * @return:
   */
  async upload() {
    const { ctx } = this;
    try {
      //files[0]表示获取第一个文件,若前端上传多个文件则可以遍历这个数组对象
      // file包含了文件名,文件类型,大小,路径等信息
     let file = ctx.request.files[0] 
     const DirPath = path.join(this.config.static.dir, ZHIPING_INTERVIEW_DIR);
     // 创建目录 确保目录的存在。如果目录结构不存在,就创建一个。
     await fse.ensureDir(DirPath);
     const prefixPath = `/public/${ZHIPING_INTERVIEW_DIR}`;
     // 自定义文件名称 path.extname 获得上传文件后缀
     const newFilename = uuidv4() + path.extname(file.filename);
     // 读取文件
     let fileObiect = fs.readFileSync(file.filepath) 
     // 将文件存到指定位置
     fs.writeFileSync(path.join(DirPath,newFilename), fileObiect)
     ctx.helper.success({
       path: `${prefixPath}${newFilename}`
     });
    } catch(err) {
      ctx.helper.error(500, '上传失败!');
    }
  }
    /**
   * @description:  删除简历
   * @param {*} param1
   * @return {*}
   */
  async delResume(prefixPathName) {
    const fileName = prefixPathName.replace(/\/public\/zhiping_interview\//g,'')
    const DirPath = path.join(this.config.static.dir, ZHIPING_INTERVIEW_DIR);
    console.log(`${DirPath}${fileName}`)
    return fs.unlinkSync(`${DirPath}${fileName}`)
  }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值