springmvc文件上传下载

1.加入jar包commons-fileupload-1.2.1.jar
commons-io-2.0.jar

2.springmvc.xml中配置bean
<bean id="nultipartResolver"
    class="org.springframework.web.multipart.commons.commonsMultipartResolver">
    <property name="defaultEncoding" value="UTF-8"></property>
    <property name="maxUploadSize" value="1024000"></property>
</bean>

3.前台页面
<form action="testFileUpload" method="POST" enctype="multipart/form-data">
        File: <input type="file" name="file"/>
        Desc: <input type="text" name="desc"/>
        <input type="submit" value="Submit"/>
    </form>

4.在cotroller中
private String savePicture(MultipartFile file, Date date, String path, int i) {
        int index = file.getOriginalFilename().lastIndexOf(".");
        String filePostfix = file.getOriginalFilename().substring(index);
        String fileName = date.getTime() + "-" + i + filePostfix;
        String dbPath = path.substring(path.lastIndexOf("upload"));
        String filePath = dbPath + "/" + fileName;
        File targetFile = new File(path, fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filePath;
    }

     private List<String> uploadPictures(MultipartFile[] files) {
        String path = WebConf.getValue("PROVIDER_INFO_CONFIRM");
        Date date = new Date();
        path += new SimpleDateFormat("yyyy/MM/dd").format(date).toString();
        List<String> filePath = new ArrayList<>();
        int i = 0;
        for (MultipartFile file : files) {
            filePath.add(savePicture(file, date, path, i++));
        }
        LOG.debug("filePath{}", filePath);
        return filePath;
    }
文件下载

    @RequestMapping("/testResponseEntity")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
        byte [] body = null;
        ServletContext servletContext = session.getServletContext();
        InputStream in = servletContext.getResourceAsStream("/files/abc.txt");
        body = new byte[in.available()];
        in.read(body);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=abc.txt");

        HttpStatus statusCode = HttpStatus.OK;

        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
        return response;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值