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<MultipartFile> 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:該類實現響應頭、文件數據(以字節存儲)、狀態封裝在一起交給瀏覽器處理以實            
       現瀏覽器的文件下載
     * <p>
     * ResponseEntity 也可作爲響應數據使用  與@ResponseBody 註解功能相似
     * 但是ResponseEntity的優先級高於@ResponseBody
     * 在不是ResponseEntity的情況下才去檢查有沒有@ResponseBody註解。
     * 如果響應類型是ResponseEntity可以不寫@ResponseBody註解,寫了也沒有關係。
     * <p>
     * 簡單粗暴的講,個人理解:
     *      @ResponseBody可以直接返回Json結果,
     *      @ResponseEntity不僅可以返回json結果,還可以定義返回的HttpHeaders和HttpStatus
     */
    @RequestMapping("/download")
    public ResponseEntity<byte[]> 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<byte[]>(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" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>文件下載</title>
</head>
<body>
<a href="/file/download?filename=<%=URLEncoder.encode("mvn.txt","UTF-8")%>">文件下載</a>
</body>
</html>

fileupload.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上傳</title>
    <script>
        <%--判斷是否填寫上傳人並已經選擇上傳文件--%>
        function check() {
            var name = document.getElementById("name").value();
            var name = document.getElementById("file").value();
            if(name==""){
                alert("請填寫上傳人");
                return false;
            }
            if(file.length==0||file==""){
                alert("請選擇上傳文件");
                return false;
            }
            return true;
        }
    </script>
</head>
<body>
<%--enctype="multipart/form-data"採用二進制流處理表單數據--%>
<form action="/file/upload" method="post" enctype="multipart/form-data">
    請選擇文件:<input id="file" type="file" name="uploadfile" multiple="multiple"/><br/>
    <%--multiple屬性選擇多個文件上傳--%>
    <input type="submit" value="文件上傳" />
</form>




</body>
</html>

springmvc.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <context:component-scan base-package="cn.com.zwz.spring.beans.file">

    </context:component-scan>

    <mvc:annotation-driven></mvc:annotation-driven>
    <mvc:default-servlet-handler/>

    <!--配置視圖解析器 :如何把handler 方法的返回值 解析爲實際的物理視圖-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <aop:aspectj-autoproxy/>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="DefaultEncoding" value="UTF-8" />
        <property name="MaxUploadSize" value="1048576" />
        <property name="MaxInMemorySize" value="4096"/>
    </bean>

</beans>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章