springmvc 实现文件上传下载,demo直接可用

package cn.com.zwz.spring.beans.file;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;



@Controller
@RequestMapping("/file")
@MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024,
        maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)
public class Load {

    @Resource
    HttpServletRequest request;


    /**
     * @return  返回相对路径RelativePath
     */
    public String RelPath() {
        String path = request.getContextPath();
        return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    }

    /**
     * @return  返回服务器目录的真实路径
     */
    public String RealPath() {
        return request.getSession().getServletContext().getRealPath("/");
    }


    @RequestMapping("/toUpload")
    public Object toUpload(){

        return "fileupload";
    }


    @RequestMapping("/upload")
    public Object upload(@RequestParam("uploadfile") List uploadfile){
        if (!uploadfile.isEmpty() && uploadfile.size() > 0) {
            for (MultipartFile file : uploadfile) {
                String originalFilename = file.getOriginalFilename();
                String dirPath = request.getServletContext().getRealPath("/upload/");
                File filePath = new File(dirPath);
                if (!filePath.exists()) {
                    filePath.mkdirs();
                }

                String newFilename = "_" + originalFilename;
                try {
                    file.transferTo(new File(dirPath + "_"+newFilename));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
            return "sucess";

    }

    @RequestMapping("/toDownload")
    public Object toDownload(){

        return "filedownload";
    }

    /**
     * 文件下载
     * ResponseEntity:该类实现响应头、文件数据(以字节存储)、状态封装在一起交给浏览器处理以实            
       现浏览器的文件下载
     * 

* ResponseEntity 也可作为响应数据使用 与@ResponseBody 注解功能相似 * 但是ResponseEntity的优先级高于@ResponseBody * 在不是ResponseEntity的情况下才去检查有没有@ResponseBody注解。 * 如果响应类型是ResponseEntity可以不写@ResponseBody注解,写了也没有关系。 *

* 简单粗暴的讲,个人理解: * @ResponseBody可以直接返回Json结果, * @ResponseEntity不仅可以返回json结果,还可以定义返回的HttpHeaders和HttpStatus */ @RequestMapping("/download") public ResponseEntity download(String filename) throws Exception { String path = request.getServletContext().getRealPath("/"); File file = new File(path+File.separator+filename); /*filename = this.getFilename(request,filename); HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment",filename); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);*/ if(file.exists()){ HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", file.getName()); return new ResponseEntity(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK); }else{ System.out.println("文件不存在,请重试..."); return null; } } public String getFilename(HttpServletRequest request,String filename) throws Exception{ String[] IEBrowserKeyWord = {"MSIE","Trident","Edge"}; String userAgent = request.getHeader("User-Agent"); for(String keyWord:IEBrowserKeyWord){ if(userAgent.contains(keyWord)){ return URLEncoder.encode(filename,"UTF-8"); } } return new String(filename.getBytes("UTF-8"),"ISO-8859-1"); } }

jsp代码:

filedownload.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.net.URLEncoder" %>


    
    文件下载


">文件下载

fileupload.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    文件上传
    


<%--enctype="multipart/form-data"采用二进制流处理表单数据--%>
请选择文件:
<%--multiple属性选择多个文件上传--%>

springmvc.xml配置



    

    

    
    

    
    
        
        
    

    

    
        
        
        
    

 

你可能感兴趣的:(Spring)