spring boot单个和批量上传文件分析

今天分享 spring boot单个和批量上传文件,这是系统的常用功能;

1、控制层代码展示:

1)单个上传:

/**
     * 上传端口关系文件
     * @param request
     * @param file
     * @param type
     * @param groupId
     *  @RequestParam("file") MultipartFile file 此设置很重要,关系到上传时设置
     * @return
     */
    @RequestMapping("/uploadFile")
    public void uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file, @RequestParam("type") String type, @RequestParam("groupId") Integer groupId){
        if( StringUtils.isEmpty(type) || Objects.isNull(groupId)){
            throw LogicException.le("参数为空");
        }
        DocumentInfo documentInfo = new DocumentInfo();
        documentInfo.setType(type);
        documentInfo.setGroupId(groupId);
        String fileName = file.getOriginalFilename();
        String mimeType = request.getServletContext().getMimeType(fileName);

        log.info("文件名称:{},和mimeType:",fileName,mimeType);
        documentInfo.setName(fileName);
        documentService.uploadFile(file,documentInfo);
        //return null;
    }

业务处理:

@Override
    public void uploadFile(MultipartFile file, DocumentInfo documentInfo) {
        String fileName = file.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
       // String mimeType = request.getServletContext().getMimeType(fileName);
        String path = "";
        String mimeType = "mimeType";
        boolean isImage = false;
        FileInputStream inputStream = null;
        BufferedReader reader = null;
        String line=null;
        File dst = null;
        try {
            if (mimeType.startsWith("image/")) { // 图片
                // It's an image.
          //      path = commonService.handleImage(uploadFiles, serialNo);
                isImage = true;

            } else {
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String dateNowStr = sdf.format(date);
                Calendar cal = Calendar.getInstance();
                path = cal.get(Calendar.YEAR) + File.separator + dateNowStr + File.separator ;
              //  String host = GlobalConfigurationReader.getProperty("system.buildWordPath") + path;
                String host = "E:\\power\\update\\" + path;//本地测试地址
              //  String host = fileDir + path;//正式环境地址
                File wordDir = new File(host);//存到临时文件目录
                if (!wordDir.exists()) {
                    wordDir.mkdirs();
                }
            //    String pathName = UUID.randomUUID() + "." + prefix;
                dst = new File(wordDir,fileName);
             //   File dst = new File(wordDir, pathName);//给文件换名称
               // file.transferTo(dst); //暂时注释掉上传接口
              //  path = path + File.separator + pathName;
           //     path = path + File.separator + fileName;
                path = path + fileName;
                //String hostPath = path + fileName;
            }

            /**
             * 上传保存到文件服务中:其实就是把文件专门保存在一个服务中
             */
         
            RestResult restResult = uploadFileManageClient.serviceUpload(file, "订单文件", null);
            log.info("返回加密文件地址:{};返回码:{};返回信息:{}",restResult.getData().toString(),restResult.getCode(),restResult.getMessage());

            /**
             * 文件内容存到数据库
             */
            StringBuilder strFlie = new StringBuilder();
            inputStream = new FileInputStream(dst);
           reader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line=reader.readLine())!=null) {
                strFlie.append(line);
            }
            log.info("文件内容:{}",strFlie.toString());//String.trim()
            documentInfo.setContent(strFlie.toString().trim());
            documentInfo.setName(fileName);
            documentInfo.setPath(path);
            documentInfoMapper.insert(documentInfo);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(null !=inputStream){
                    inputStream.close();
                }
                if(null !=reader){
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

 

2)批量上传:和单个上传类似,只是传文件时时数组格式,控制层代码如下:

 /**
     * 批量上传关系文件
     * @param request
     * @param files
     * @param type
     * @param groupId
     * @RequestParam("file") MultipartFile[] files 主要参数
     * @return
     */
    @RequestMapping("/batchUploadFile")
    public void batchUploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile[] files, @RequestParam("type") String type, @RequestParam("groupId") Integer groupId){
        if( StringUtils.isEmpty(type) || Objects.isNull(groupId)){
            throw LogicException.le("参数为空");
        }
        DocumentInfo documentInfo = new DocumentInfo();
        documentInfo.setType(type);
        documentInfo.setGroupId(groupId);
        for(MultipartFile flie : files){//循环单个上传
            String fileName = flie.getOriginalFilename();
            String mimeType = request.getServletContext().getMimeType(fileName);
            log.info("文件名称:{},和mimeType:",fileName,mimeType);
            documentInfo.setName(fileName);
            documentService.uploadFile(flie,documentInfo);
        }

    }

业务层代码都一样。

3、postman测试上传:

 

4、单个下载:

控制层

/**
     * 单个下载文件
     * @param request
     * @param response
     * @param pid
     * @return
     */
    @RequestMapping("/downFileByFileKey")
    public void downFileByFileKey(HttpServletRequest request, HttpServletResponse response,
                                                                     @RequestParam("pid") Integer pid){
        if( Objects.isNull(pid)){
            throw LogicException.le("参数为空");
        }
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            downloadService.downloadFileByFileKey(request,pid,response,bis,bos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null)
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (bos != null)
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }

 业务层:

 @Override
    public void downloaFileByFileKey(HttpServletRequest request, Integer pid, HttpServletResponse response, BufferedInputStream bis, BufferedOutputStream bos) throws Exception {
        DocumentInfo documentInfo = documentInfoMapper.selectByPrimaryKey(pid);
        String fileKey = documentInfo.getFileKey();
        if(StringUtils.isEmpty(fileKey)){
            throw new NullPointerException("文件索引id为空");
        }
        Response resultResponse = dssFileManageClient.serviceDownload(fileKey);
        log.info("取到的文件信息:{}",resultResponse.body());
        // String prefix = "";
        String fileName = documentInfo.getName();//文件名称
        String agent = request.getHeader("User-Agent").toLowerCase();
        boolean isMSIE = (agent != null && (agent.indexOf("msie") != -1 || (agent.indexOf("rv") != -1 && agent.indexOf("firefox") == -1)));
        if (isMSIE) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment; filename=\""+ fileName+"\"");
       /* if(StringUtils.isNotBlank(suffix) && Objects.equals("pdf",suffix.toLowerCase())){
            response.setContentType("application/pdf;charset=GBK");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "inline;filename="+ imageRealName);
        }else{
            response.setContentType("image/jpg");
        }*/
        bis = new BufferedInputStream(resultResponse.body().asInputStream());
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        bos.flush();
        log.info("下载文件成功:{}",fileName);
    }

 客户端下载测试:成功下载

这就是单个下载文件的分享,多个下载也是同理。 

上传和下载分享完毕,此方案不仅适合springboot 还适用 springMVC或Struts框架!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

寅灯

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

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

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

打赏作者

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

抵扣说明:

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

余额充值