码迷,mamicode.com
首页 > 编程语言 > 详细

springmvc--文件上传下载

时间:2016-02-03 00:12:51      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

一.文件下载

// 文件下载
    @RequestMapping("/testResponseEntity")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
        byte[] body = null;
        
        InputStream in = session.getServletContext().getResourceAsStream("/file/abc.txt");
        System.out.println("inputstream" + in);
        body = new byte[in.available()];
        in.read(body);
        
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=abc.txt");
        
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, HttpStatus.OK);
        return response;
    }

二.文件上传

springmvc为文件上传提供了直接的支持,这种支持是通过即插即用的MultipartResolver实现的。

spring用jakarta commons FileUpload技术实现了MultipartResolver实现类:CommonsMultipartResolver

下面看如何来实现

1.引进如下jar包

commons-fileupload.jar

commons-io.jar  (<-上面的jar的依赖包)

2.springmvc的配置文件中,配置如下

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        </bean>

3.前台代码如下:

<form action="testFileUpload" enctype="multipart/form-data" method="POST">
    File : <input type="file" name="file"><br>
    Desc : <input type="text" name="desc"><br>
    <input type="submit" value="Submit">
    </form>

4.后台代码如下:

    // 文件上传
    @RequestMapping(value="/testFileUpload")
    public String testFileUpload(@RequestParam("desc") String desc,
            @RequestParam("file") MultipartFile file) throws IOException{
        System.out.println("desc: "+ desc);
        System.out.println("file name: " + file.getOriginalFilename());
        System.out.println("file inputstream" + file.getInputStream());
        return "success";
    }

 

springmvc--文件上传下载

标签:

原文地址:http://www.cnblogs.com/mianteno/p/5178788.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!