首页 > 代码库 > springMVC文件的上传与下载

springMVC文件的上传与下载

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 = http://www.mamicode.com/"/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 = "http://www.mamicode.com/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文件的上传与下载