node文件上传(不用模块)

原创
2017/07/18 15:00
阅读数 60

前端代码:

react:

  1. render() {
  2. let url = this.state.file;
  3. return <div className="input-group">
  4. <input id="file" onChange={(e) => this.handleChange(e)} type="file" className="form-control" placeholder="请选择文件" />
  5. <span className="input-group-btn">
  6. <button onClick={() => this.addResource()} className="btn btn-primary" type="button">上传文件</button>
  7. </span>
  8. </div>
  9.  

js:

  1. handleChange(e: any) {
    1. e.preventDefault();
    2. let target = e.target;
    3. let files = target.files;
    4. this.setState({
    5. file: files[0]
    6. })
    7. }
  2. addResource() {
    1. if (!this.state.file) {
      1. alert('请选择文件');
      2. return;
    2. }
    3. let formData = new FormData();
    4. formData.append('fileData', this.state.file)
    5. fetch('/XXXXX ', {
      1. method: 'POST',
      2. credentials: "include",
      3. body: formData,
      4. headers: {
        1. "accept": "application/json"
        2. },
    6. }).then((res) => {
    7. console.log(res);
    8. return res.json();
    9. }).then((res) => {
      1. })
    10. }
  3.  

node:

    

  1. export const add: Middleware = async (ctx, next) => {
    1. let req = ctx.req;
    2. let body = "";
    3. let boundary: any = ctx.headers['content-type'].split(';')[1].replace('boundary=', '');
    4. req.setEncoding("binary");
    5. await new Promise((ok, fail) => {
      1. req.on('data', (chunk) => {
        1. body += chunk;
        2. })
      2. req.on('end', () => {
        1. let file = body.split(('--' + boundary).replace(" ", "")),
        2. i = 1;
        3. for (let i = 1, c = file.length - 1; i < c; i++) {
          1. let something = querystring.parse(file[i], "\r\n", ": ");
          2. file[i].match(/Content-Type: (.*)\r\n/)
          3. if (something['Content-Type']) {
          4. //把文件名改为时间戳
          5. let type = something['Content-Disposition'].split('filename=')[1].replace(/"/g, '').trim().split('.')
          6. let fileName = String(new Date().getTime()) + '.' + type[type.length - 1]
          7. let contentType = something['Content-Type']
          8. let upperBoundary = body.indexOf(contentType) + contentType.length//获取文件二进制数据开始位置,即contentType的结尾
          9. let shorterData = body.substring(upperBoundary) // 替换开始位置的空格和结尾的空格
          10. let binaryDataAlmost = shorterData.trim();
          11. let binaryData = binaryDataAlmost.substring(0, binaryDataAlmost.indexOf(('--' + boundary + '--').replace(" ", ""))) // 去除数据末尾的额外数据,即: "--"+ boundary + "--"
          12. let homeDir = path.resolve(__dirname, '../../..', 'resource')
          13. if (mkdirsSync(homeDir)) {
          14. try {
            1. fs.writeFileSync(path.join(homeDir, fileName), binaryData, 'binary');
            2. console.log('上传完成');
            3. ctx.body = {
            4. msg: '上传完成',
            5. code: 1
            6. }
            7. ok();
          15. } catch (e) {
            1. console.log(e);
            2. throw Boom.badImplementation();
          16. }
          17. } else {
            1. let Err = Boom.badImplementation();
            2. ctx.throw(Err);
          18. }
          19. } else {
            1. let Err = Boom.badData("上传的不是文件");
            2. ctx.throw(Err);
          20. }
        4. }
      3. })
    6. })
  2. }

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部