前端ajax异步上传文件+SpringMVC处理上传文件

mark一下以防自己以后再次遇到,也是给同行们一个参考。先说下我的需求:

    前端我需要给用户一个上传文件页面,用户点击上传后,不会像提交form一样跳转,而是在上传页面下方显示上传情况(正在分析/上传出现错误/上传成功),当然首选ajax来实现了
    后端的话我拿到文件,将它保存在一个临时位置,待我分析完毕上传DB后,将临时文件删除。所以我这里并不是简单的文件上传,中间还要将原始文件进行一个分析再保存,并且将原始文件删除。

ok,

先从前端搞起:
我前端是用React写的,先贴源码:

import React from 'react';
import $ from 'jquery';

export default class Upload extends React.Component {
  constructor(props) {
    super(props);
    this.state = {infor: ''};
    this.uploadvcf = this.uploadvcf.bind(this);
  }

  uploadvcf(e) {
    e.preventDefault(); //取消form的默认提交功能,只响应该uploadvcf()
    this.setState({infor: 'file is analyzing in back-end, please waiting.....'});
    const form = $('form')[0];
    const data = new FormData(form); //这里要设置

    $.ajax({
      type: 'POST',
      encType: 'multipart/form-data', //表明上传类型为文件
      processData: false, //这里设置成false,表明上传数据不需转换成字符串
      contentType: false,
      cache: false,
      url: 'uploadvcf',
      data: data,
      success: response => {
        this.setState({infor:response});
      }
    });
  }

  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col-md-offset-1 col-md-11">
            <h3>Upload File</h3>
            <div className="col-md-8">
              <form className="" method="POST"> //form
                  <div className="form-group">
                    <label>File1</label>
                    <input type="file" className="form-control" name="files"/>
                  </div>
                  <div className="form-group">
                    <label>File2</label>
                    <input type="file" className="form-control" name="files"/>
                  </div>
                  <div className="form-group">
                    <label>File3</label>
                    <input type="file" className="form-control" name="files"/>
                  </div>
                <div className="col-md-offset-8 col-md-4">
                  <button className="btn btn-primary" onClick={this.uploadvcf}>Submit</button>
                </div>
              </form>
              <div>
                <h4></h4>
              </div>
            </div>
            <div className="col-md-8">
              <h4 id="info">{this.state.infor}</h4>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
上传页面:

这里写图片描述

再说后端:
先贴源码:

@RequestMapping(value="uploadvcf", method=RequestMethod.POST)
public @ResponseBody String uploadFile(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {

        if(files != null && files.length>0) { //循环每一个文件
            for(int i=0; i<files.length;i++) {
                MultipartFile file = files[i];
                try {
                    analyzeFile(file); //分析文件,方法在下边

                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                    return "file format is error";
                } catch (Exception e) {
                    return "analyzing error when analyzing " + file.getOriginalFilename();
                }
            }

            return "upload successfully";
        } else {
            return "You failed to upload because the files is empty";
        }
    }

//分析方法  
private void analyzeFile(MultipartFile file) throws Exception {
        if(!file.isEmpty()) {
            String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"; //声明一个临时文件保存路径
            File dir = new File(filePath);
            if(! dir.exists()) {
                dir.mkdir();
            } //假如路径不存在 生成

            String path = filePath + file.getOriginalFilename();
            File tempFile = null;
            //save to the /upload path
            try {
                tempFile =  new File(path);
                file.transferTo(tempFile);//将上传的文件保存到临时文件
                //analyze the file
                pointService.uploadFile(path);

                tempFile.delete(); //分析完成,删除临时文件
            } finally {
                tempFile.delete(); //假如分析过程出错,也要删除临时文件
            }

        }
    }

嗯,大约就是这样子。mark下

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Frank Lin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值