欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Egg.js 中 AJax 上传文件获取参数的方法

程序员文章站 2022-06-11 15:58:34
依赖 formidable 代码 前端
...

依赖

formidable

代码

前端

<fieldset style="margin: 20px; padding: 20px;">
 <legend>单文件,ajax</legend>
 <form id="form3">
  <div>
   <input type="text" id="customname" placeholder="自定义文件名" />
  </div>
  <div>
   <input type="file" class="file" />
  </div>
  <div>
   <input type="submit" value="上传">
  </div>
 </form>
</fieldset>

<fieldset style="margin: 20px; padding: 20px;">
 <legend>多文件,ajax</legend>
 <form id="form4">
  <div>
   <input type="file" class="file" multiple />
  </div>
  <div>
   <input type="submit" value="上传" />
  </div>
 </form>
</fieldset>
<script>
 $(function () {
  const _csrf = "{{ ctx.csrf | safe }}";
  $('form').submit(function (e) {
   e.preventdefault();
   const formdata = new formdata();
   const filelist = $(this).find('.file')[0].files;
   let index = 0;
   for (let key of filelist) {
    formdata.append('file' + index, key);
    index++
   }
   formdata.append('isajax', 'yes');
   formdata.append('customname', $(this).find('#customname').val() || '');
   $.ajax({
    url: '/admin/file/upload?_csrf=' + _csrf,
    data: formdata,
    method: 'post',
    contenttype: false,
    processdata: false,
    success: function (result) {

    },
    error: function (responsestr) {
     alert("error", responsestr);
    }
   });
  });
 });
</script>

node

'use strict';
const fs = require('fs');
const path = require('path');
const awaitwritestream = require('await-stream-ready').write;
const sendtowormhole = require('stream-wormhole');
const formidable = require("formidable");
const controller = require('../../core/base_controller');
class filecontroller extends controller {
 async parse(req) {
  const form = new formidable.incomingform();
  return new promise((resolve, reject) => {
   form.parse(req, (err, fields, files) => {
    resolve({ fields, files })
   })
  });
 }
 /**
 * 上传文件,兼容单文件和多文件
 * @param customname 单文件自定义文件名
 * @param isajax 上传方式
 */
 async upload() {
  const { ctx, logger } = this;
  const extraparams = await this.parse(ctx.req);
  let { multiplefile, customname, isajax } = extraparams && extraparams['fields'];
  logger.info(multiplefile, customname, isajax);
  if (isajax === 'yes') {
   const urls = [];
   for (let key in extraparams.files) {
    const file = extraparams.files[key];
    logger.info('file.name', file.name);
    logger.info('customname', customname);
    const stream = fs.createreadstream(file.path);
    const filename = customname ? (customname + path.extname(file.name)) : file.name;
    const target = path.join(this.config.basedir, 'app/public/upload', filename);
    const writestream = fs.createwritestream(target);
    try {
     await awaitwritestream(stream.pipe(writestream));
    } catch (err) {
     await sendtowormhole(stream);
     throw err;
    }
    urls.push(target);
   }
   this.success({ urls })
  }
 }
}
module.exports = filecontroller;

总结

以上所述是小编给大家介绍的egg.js 中 ajax 上传文件获取参数,希望对大家有所帮助