springMVC入门--5.文件上传下载

1.依赖包

commons-io-2.4.jar
commons-fileupload-1.2.2.jar

2.文件上传,依赖于MultipartFile

xml配置:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSizePerFile" value="500000000"></property>
        <property name="defaultEncoding" value="utf-8"></property>
        <property name="resolveLazily" value="true"></property>
</bean>

代码示例:

@RequestMapping("/testUpload")
    public String testJson(@RequestParam("file") MultipartFile file,
            @RequestParam("msg") String msg,HttpServletRequest request) throws IllegalStateException, IOException{
        if(!file.isEmpty()){
            //上传路径
            /*String path=request.getServletContext().getRealPath("/images/");*/
            String path="D:";
            //上传文件名
            String fileName=file.getOriginalFilename();
            File filepath=new File(path,fileName);
            //判断路径是否存在,如果不存在就创建一个
            if(!filepath.getParentFile().exists()){
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到目标文档
            file.transferTo(filepath);
        }
        return "hello";
    }

如果表单中有多个文件上传,可以使用MultipartFile[]

3.文件下载

@RequestMapping("/testDownLoad")
    public ResponseEntity<byte []> download(HttpServletRequest request) throws IOException{
        //下载文件路径
        /*String path=request.getServletContext().getRealPath("/images/");*/
        String path="D:";
        String filename="DSC_1240.JPG";
        File file=new File(path,filename);
        HttpHeaders headers = new HttpHeaders();  
        //下载显示的文件名,解决中文名称乱码问题  
        String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");

        //通知浏览器以attachment(下载方式)打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName); 
        //application/octet-stream : 二进制流数据(最常见的文件下载)。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                headers, HttpStatus.CREATED);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值