温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-08-20 19:10:14 来源:脚本之家 阅读:162 作者:公旦 栏目:web开发

依赖

formidable

代码

前端

<fieldset >
 <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 >
 <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 上传文件获取参数,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI