springmvc+vue实现文件上传

需求:spring+vue实现文件上传

思路
使用Element UI中的上传插件,在进行分装,然后传入java,使用java上传文件之后,保存文件所对应的url地址,以便下次访问时候使用。
前端代码
插件的使用具体见element UI的官方文档
 <el-upload
          :on-success="uploadSuccess"
          :headers="uploadHeaders"
          :data="fileUploadParams"
          class="upload-demo"
          accept=".csv"
          ref="upload"
          :action=uploadUrl
          :file-list="fileList"
          :auto-upload="false">
          <el-button slot="trigger" size="big" type="primary">选取文件</el-button>

          <el-button style="margin-left: 10px;" size="big" type="success" @click="submitUpload"
                     :disabled="buttonDisabled">上传到服务器
          </el-button>
  </el-upload>
  import service from '@/utils/request.js'
  import { getToken } from '@/utils/auth.js'
 export default {
    name: 'check-file-upload',
    data() {
      return {
        buttonDisabled: false,
        uploadHeaders: {},
        uploadUrl: process.env.BASE_API + '/fileupload/statement',
        times: null,
        fileUploadParams: {},
        getTimesUrl: '/fileuploadrecord/getTimes',
        fileList: []
      }
    },
    created() {
      this.getData()
      this.loadHeaders()
    },
    methods: {
      uploadSuccess(response, file, fileList) {
        if (response.code === 20000) {
          this.$alert(response.message, 'Tips', {
            confirmButtonText: '确定'
          })
        }
      },
      loadHeaders() {
        var token = getToken()
        if (token) {
          this.uploadHeaders.Authorization = token
        }
      },
      getData() {
        service.get(this.getTimesUrl).then((res) => {
          res.dataList.forEach((e) => {
            if (this.times === null) {
              this.times = e
              this.fileUploadParams.startTime = e
            } else {
              this.times = this.times + '_' + e
              this.fileUploadParams.endTime = e
            }
          })
        })
      },
      submitUpload() {
        this.$refs.upload.submit()
        this.buttonDisabled = true
      }
    }
请求参数

java代码
  @RequestMapping(value = "/statement", method = RequestMethod.POST)
    @ResponseBody
    public String uploadStatement(DefaultMultipartHttpServletRequest request) {
        ResultInfo<String> resultInfo = new ResultInfo<String>();
        resultInfo.setCode(Constants.RESPONSE_OK);
        FileUploadRecord fileUploadRecord = new FileUploadRecord();
        //上传中用到的流
        InputStream inputStream = null;
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;

        byte[] bytes = new byte[2048];
        int n = -1;

        String fileName = "";
        String startTime = "";
        String endTime = "";
        String token = "";
        String authorization = request.getRequest().getHeader("Authorization");

        if (StringUtils.isBlank(authorization)) {
            resultInfo.setMessage("参数错误");
            logger.error("the params " + JSONObject.toJSONString(request.getRequest()));
            return JSONObject.toJSONString(resultInfo);
        }
        User userInfo = userService.getUserInfo(authorization);

        Map<String, String[]> requestParameterMap = request.getParameterMap();
        if (requestParameterMap.size() != 2) {
            resultInfo.setMessage("参数错误");
            logger.error("the params " + JSONObject.toJSONString(requestParameterMap));
            return JSONObject.toJSONString(resultInfo);
        }

        String[] startTimes = requestParameterMap.get(Constants.UPLOAD_PARAM_STARTTIME);
        startTime = startTimes[0];
        String[] endTimes = requestParameterMap.get(Constants.UPLOAD_PARAM_ENDTIME);
        endTime = endTimes[0];

        MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
        if (multiFileMap.size() != 1) {
            logger.error("error,params:" + JSONObject.toJSONString(multiFileMap));
            resultInfo.setMessage("error");
            return JSONObject.toJSONString(resultInfo);
        }
        List<MultipartFile> files = multiFileMap.get("file");
        MultipartFile multipartFile = files.get(0);
        String originalFilename = multipartFile.getOriginalFilename();
        String[] strings = originalFilename.split("\\.");
        logger.info("the file name is :" + multipartFile.getOriginalFilename());
        if (strings.length != 2) {
            resultInfo.setMessage("文件名格式错误");
            return JSONObject.toJSONString(resultInfo);
        }
        //拼接上传的文件名
        fileName = startTime + "_" + endTime + "." + strings[1];

        try {
            inputStream = multipartFile.getInputStream();
            bufferedInputStream = new BufferedInputStream(inputStream);
            String uploadFilePath = PropertyUtils.readUploadFilePathProperty();
            File file = new File(uploadFilePath + java.io.File.separator + fileName);
            if (file.exists() == true) {
                logger.error("the file has exists,the path is:" + file.getPath());
                resultInfo.setMessage("the file has exits");
                return JSONObject.toJSONString(resultInfo);
            } else {
                file.createNewFile();
            }
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
            while ((n = bufferedInputStream.read(bytes, 0, bytes.length)) != -1) {
                String str = new String(bytes, 0, n);
                bufferedOutputStream.write(bytes, 0, n);
            }
            fileUploadRecord.setUploader(userInfo.getUsername());
            fileUploadRecord.setFileName(fileName);
            fileUploadRecord.setFilePath(file.getAbsolutePath());
            fileUploadRecordService.addFileUploadRecord(fileUploadRecord);
            resultInfo.setMessage("success");
        } catch (Exception e) {
            logger.error("upload file error,the reason is:" + e.getMessage());
            resultInfo.setMessage("upload file error");
            return JSONObject.toJSONString(resultInfo);
        } finally {
            try {
                bufferedInputStream.close();
                bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return JSONObject.toJSONString(resultInfo);
    }
其中存在的问题
1.因为是前后端分离开发,所以发现是session并没法使用,所以无法区分用户名,这个问题在另外一篇博客中会提到。
2.文件上传之后,接受的对象并不是一样的,在这个项目中是用到了DefaultMultipartHttpServletRequest这个类来接。
3.其中还会涉及到大文件上传的问题,这个问题还没有解决,但是网上有解决方法:http://www.cnblogs.com/daoqidelv/p/6884223.html
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页