欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

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

时间:2022-04-12 09:20:03|栏目:JavaScript代码|点击:

依赖

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;

总结

上一篇:利用bootstrapValidator验证UEditor

栏    目:JavaScript代码

下一篇:小程序中如何绘制思维导图详解

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

本文地址:http://www.codeinn.net/misctech/198948.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有