14.SpringMVC the file upload and download

SpringMVC realize the file upload support by MultipartResolver (multi-component parser) object.

MultipartResolver is an interface object, we need to complete the work of uploading files through its implementation class CommonsMultipartResolver.

1. The need to upload jar package commons-fileupload.jar commons-io.jar

2. Using MultipartResolver objects Bean configuration in 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <context:annotation-config/>
    <context:component-scan base-package="com.wxy.controller"/>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8" />
        <property name="maxUploadSize" value="2097152" />
    </bean>
</beans>

3.fileUpload.jsp upload page

<% @ Page contentType = " text / HTML; charset = UTF-. 8 " Language = " Java "  %> 
< HTML > 
< head > 
    < title > File Upload </ title > 
    < Script > 
        <% - determines whether fill upload who has selected and uploaded -%> 
        function Check () {
             var name = document.getElementById ( " name " ) .Value ();
             var name = document.getElementById("File " ) .Value ();
             IF (name == " " ) { 
                Alert ( " please fill out the upload man " );
                 return  false ; 
            } 
            IF (file.length == 0 || File == " " ) { 
                Alert ( " Please select the file upload " );
                 return  to false ; 
            } 
            return  to true ; 
        } 
    </ Script > 
</ head > 
<body > 
<% - the enctype = " multipart / form-Data " in binary form data stream processing - %> 
< form Action = "$ {} /fileUpload.action pageContext.request.contextPath" Method = "POST" the enctype = "multipart / form-the Data" the onsubmit = "return the Check ()" > 
    Upload person: < the INPUT the above mentioned id = "name" of the type = "text" name = "name" /> < br /> 
    select the file: < the INPUT the above mentioned id = "file" type="file" name= "UploadFile" Multiple = "Multiple" /> < br /> 
    <% - Multiple select multiple files to upload properties - %> 
    < INPUT type = "Submit" value = "Upload File"  /> 
</ form > 
< / body > 
</ HTML >

4.fileDownload.jsp download page

<%@ 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="${pageContext.request.contextPath}/download.action?filename=<%=URLEncoder.encode("图像.txt","UTF-8")%>">文件下载</a>
</body>
</html>

5.FileUploadAndDownloadController.java file upload and download controller class

package com.wxy.controller;

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.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

@Controller("controller")
public class FileUploadAndDownloadController {
    @RequestMapping("/tofileUpload")
    public String toupload(){
        return "fileUpload";
    }
    @RequestMapping("/tofiledownload")
    public String todownload(){
        return "download";
    }
    @RequestMapping("/fileUpload.action")
    public String handleFormUpload(@RequestParam("name") String name,
                                   @RequestParam("uploadfile") List<MultipartFile> uploadfile, HttpServletRequest request) {
        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 = name +"_" + originalFilename;
                try {
                    file.transferTo(new File(dirPath + "_"+newFilename));
                } catch (Exception e) {
                    e.printStackTrace();
                    return "error";
                }
            }
            return "success";
        } else {
            return "error";
        }
    }
    @RequestMapping("/download.action")
    public ResponseEntity<byte[]> filedownload(HttpServletRequest request,String filename) throws Exception{
        String path = request.getServletContext().getRealPath("/upload");
        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<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    }
    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");
    }
}

 

Guess you like

Origin www.cnblogs.com/deityjian/p/11499046.html