美文网首页Java
SpringMVC-附件上传及下载

SpringMVC-附件上传及下载

作者: 张明学 | 来源:发表于2020-06-15 08:25 被阅读0次

附件的上传的http请求体的数据格式有着特殊的要求,因此需要有特殊的方式解析这种类型的http报文。SpringMVC提供好了解决方法。CommonsMultipartResolver

配置CommonsMultipartResolver

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--设置请求编码-->
    <property name="defaultEncoding" value="UTF-8"/>
    <!-- 临时存放目录,这里不是指上传附件存放的目录,是内部解析的时候临时写的一个目录 -->
    <!--<property name="uploadTempDir" value="WEB-INF/temp"/>-->
    <!--设置允许单个上传文件的最大值,不要在这里配置-->
    <!--<property name="maxUploadSizePerFile" value="31457280"/>-->
    <!--延迟解析,在Controller中抛出异常-->
    <property name="resolveLazily" value="true"/>
</bean>

Controller中使用MultipartFile接收解析后的附件数据

@RequestMapping("/upload")
    public String info(@RequestParam(value = "file") List<MultipartFile> multipartFileList,
                       String remark,
                       HttpServletRequest request) {
        String msg = "";
        // 判断文件是否上传
        if (!multipartFileList.isEmpty()) {
            // todo 实际开发不会放到项目内部文件中,须要存贮在外部的设备中
            // 设置上传文件的保存目录
            String basePath = request.getServletContext().getRealPath("/upload/");
            // 判断文件目录是否存在
            File uploadFile = new File(basePath);
            if (!uploadFile.exists()) {
                uploadFile.mkdirs();
            }
            for (MultipartFile multipartFile : multipartFileList) {
                String originalFilename = multipartFile.getOriginalFilename();
                if (originalFilename != null && !originalFilename.equals("")) {
                    try {
                        // 对文件名做加UUID值处理
                        originalFilename = UUID.randomUUID() + "_" + originalFilename;
                        File saveFile = new File(basePath, originalFilename);
                        log.info("{}存贮在{}", originalFilename, saveFile.getPath());
                        // 写操作
                        multipartFile.transferTo(saveFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                        msg = "文件上传失败!";
                    }
                } else {
                    msg = "上传的文件为空!";
                }
            }
            msg = "文件上传成功!";
        } else {
            msg = "没有文件被上传!";
        }
        // 其它参数和
        log.info("remark={}", remark);
        request.setAttribute("msg", msg);
        return "success";
    }

上传页面,指定http报文的数据格式是multipart/form-data

<form action="/demo/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" multiple="multiple"><br>
    <input type="text" name="remark"><br>
    <input type="submit" value="上传">
</form>

附件下载,返回ResponseEntity<byte[]>

    @RequestMapping(value = "/download")
    public ResponseEntity<byte[]> fileDownload(String filename, HttpServletRequest request) throws IOException {
        String path = request.getServletContext().getRealPath("/upload/");
        File file = new File(path + filename);
        filename = this.getFilename(request, filename);
        // 设置响应头通知浏览器下载
        HttpHeaders headers = new HttpHeaders();
        // 将对文件做的特殊处理还原
        filename = filename.substring(filename.indexOf("_") + 1);
        headers.setContentDispositionFormData("attachment", filename);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
    }

    // 根据不同的浏览器进行编码设置,返回编码后的文件名
    private String getFilename(HttpServletRequest request, String filename) throws UnsupportedEncodingException {
        String[] IEBrowerKeyWords = {"MSIE", "Trident", "Edge"};
        String userAgent = request.getHeader("User-Agent");
        for (String keyword : IEBrowerKeyWords) {
            if (userAgent.contains(keyword)) {
                return URLEncoder.encode(filename, "UTF-8");
            }
        }
        return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
    }

相关文章

网友评论

    本文标题:SpringMVC-附件上传及下载

    本文链接:https://www.haomeiwen.com/subject/myzqxktx.html