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

springMVC文件的上传与下载

时间:2017-07-14 18:06:56      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:coding   rac   exist   乱码   method   批量上传   response   文件上传   servlet   

1.文件上传

springmvc中只需要配置上传组件,然后配合使用MultipartFile,就可以轻松实现单个文件上传和批量上传,而且上传的文件类型和大小都可以在springmvc 配置文件中配置。

pom文件中增加:

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>${fileupload.version}</version>
</dependency>

springMVC配置文件中增加multipartResolver:

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>40000000</value><!-- 文件最大上传限制 40M以内 -->
        </property>
        <property name="maxInMemorySize" value="2048" /> 
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>

上传代码:

@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
public Result fileUpload(HttpServletRequest request) {
        Result result = new Result();        

        List<MultipartFile> fileList = getFile(request);

        return result; 
}

/**
     * 从request中获取文件
     * @param request
     * @return
     */
    public static List<MultipartFile> getFile(HttpServletRequest request) {
        List<MultipartFile> result = null;
        try {
            result = new ArrayList<MultipartFile>();
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = mRequest.getFileMap();
            for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext();) {
                Map.Entry<String, MultipartFile> entry = it.next();
                MultipartFile mFile = entry.getValue();
                String fileSizeLimit = PropertyUtils.getConfig("fileSizeLimit");//获取配置文件中的文件大小最大限制
                if (mFile.getSize() > Long.parseLong(fileSizeLimit)) {
                    String fname = mFile.getOriginalFilename();
throw new Exception(fname + "文件大小超过最大限制");
                }
                result.add(mFile);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

 

2.文件下载

基于ResponseEntity实现

@RequestMapping("/testHttpMessageDown")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
    File file = new File("E://123.jpg");
    byte[] body = null;
    InputStream is = new FileInputStream(file);
    body = new byte[is.available()];
    is.read(body);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", "attchement;filename=" + file.getName());
    HttpStatus statusCode = HttpStatus.OK;
    ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
    return entity;
}

Java通用下载实现(这里用的GET方法方便浏览器测试)

@RequestMapping(value = "/fileDownload", method = RequestMethod.GET)
    public Result fileDownload(@RequestParam String filePath, HttpServletRequest request,
        HttpServletResponse response) {
        Result result = new Result();

        File file = new File("E://123.jpg");
        if (!file.exists()) {
            System.Out.println("文件不存在");
            return result;
        }

        try {
            response.reset(); //设置ContentType            
            response.setContentType("application/octet-stream; charset=utf-8");
            String fileName = new String(file.getName().getBytes("utf-8"), "ISO-8859-1"); //处理中文文件名中文乱码问题
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            IOUtils.copy(new FileInputStream(file), response.getOutputStream());
        }
        catch (Exception e) {
            System.Out.println("文件下载失败");
            return result;
        }

        return result;
    }

 

springMVC文件的上传与下载

标签:coding   rac   exist   乱码   method   批量上传   response   文件上传   servlet   

原文地址:http://www.cnblogs.com/Jason-Xiang/p/7171647.html

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