文件上傳+下載

1.文件上傳

1)Springmvc下上傳兩個方式

  • CommonsMultipartResolver:利用commons-fileupload中jar。
  • StandardServletMultipartResolver:Servlet3.0以上版本,利用Servlet中Part接口。

 

補充說明:html

HttpServletRequest在Servlet3.0新增對Part獲取java

public Collection<Part> getParts() throws IOException, ServletException;
public Part getPart(String name) throws IOException, ServletException;

 

2)StandardServletMultipartResolver方式流程

  • 配置

web.xml:在DispatcherServlet加入<multipart-config>配置git

<!--Servlet3.0配置文件上傳參數-->
<multipart-config>
    <!--<location>D:\\upload</location>-->
    <!--<max-file-size>1024</max-file-size>-->
    <!--<max-request-size>1024</max-request-size>-->
    <!--<file-size-threshold>1</file-size-threshold>-->
</multipart-config>

說明:測試發現單獨配置max-file-size並不生效,必須還要配置max-request-size和file-size-threshold標籤;另外超過文件大小時拋出的異常,並無讓全局統一異常處理,因此把文件大小判斷放入代碼中。web

spring-mvc.xml:spring

<!--spring集成servlet3.0文件上傳-->
<bean id="multiPart" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>
  • 代碼
@Controller
@RequestMapping("file")
public class FileController {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);
    private static final long FILE_MAX_SIZE= 5*1025*1024;//5M

    @RequestMapping("upload")
    @ResponseBody
    public String upload(String name ,Part file) throws IOException,DemoException{
        if(file.getSize() > FILE_MAX_SIZE){
            throw new DemoException("文件過大");
        }

        //獲取文件名
        String fileName = PartUtils.getFileName(file);
        
        InputStream is = file.getInputStream();
        FileUtils.copyInputStreamToFile(is, new File("D:\\upload\\" + fileName));
        
        return name+":"+fileName;
    }

    @RequestMapping("/download")
    public void download(String fileKey,HttpServletResponse response) throws IOException,DemoException{
        String fileName = fileKey;
        File file = new File("D:\\upload\\"+fileName);
        if(!file.exists()){
            throw new DemoException("文件不存在");
        }

        //設置文件名,以及中文名解決
        response.setHeader("Content-Disposition", "attachment; filename="+java.net.URLEncoder.encode(fileName, "UTF-8"));
        OutputStream os = response.getOutputStream();

        //copy方法中對各"流"進行close()
        FileUtils.copyFile(file,os);
    }
}

PartUtils:因爲從Header中獲取文件名api

public class PartUtils {
    private static final String HEAD_CONTENT = "content-disposition";
    private static final String FILE_KEY = "filename=\"";

    public static String getFileName(Part part){
        //格式:form-data; name="file"; filename="QQ圖片20160809091952.jpg"
        String headContent = part.getHeader(HEAD_CONTENT);

        int startPos = headContent.indexOf(FILE_KEY) + FILE_KEY.length();
        if(startPos < 0){
            return null;
        }

        int endPos = headContent.indexOf("\"",startPos+1);

        return headContent.substring(startPos,endPos);
    }
}

demo-web下pom.xml引入:spring-mvc

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

index.htmlmvc

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>文件上傳測試</h1>
    <form method="post" action="/demo-web/file/upload.do" enctype="multipart/form-data">
        <input type="file" name="file"/><br>
        <input type="text" name="name"/><br>
        <input type="submit"/>
    </form>
</body>
</html>
  • 測試

 

2.文件下載

代碼見上面FileController中download方法。app

只需注意文件名中文亂碼解決:ide

java.net.URLEncoder.encode(fileName, "UTF-8");

 

3. Spring MVC 4.2.4.RELEASE 中文文檔

pdf下載地址:

https://www.gitbook.com/book/linesh/spring-mvc-documentation-linesh-translation/details

相關文章
相關標籤/搜索