SpringMVC文件的上傳與下載


文件的上傳

第一步:導入依賴,在pom.xml中配置

  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
  </dependency>
  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
  </dependency>

第二步:配置文件上傳解析器,在springMVC.xml中配置

<!--文件上傳的解析器,使用spring表達式設置上傳文件大小最大值-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="#{1024*1024}"/>
</bean>

第三步:修改表單,加入屬性enctype="multipart/form-data"

  application/x-www-form-urlencoded不是不能上傳文件,是只能上傳文本格式的文件,multipart/form-data是將文件以二進制的形式上傳,這樣可以實現多種類型的文件上傳。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/save" method="post" enctype="multipart/form-data">
    用戶名:<input type="text" name="username"/><br/>
    頭像:<input type="file" name="file"/><br/>
    <input type="submit" value="保存"/>
</form>

<a href="/download?name=xxx.png">下載</a>

</body>
</html>

第四步:使用springMVC接收文件

@Controller
public class UploadController {
    //servletContext上下文對象,可以直接注入
    @Autowired
    private ServletContext servletContext;
    @RequestMapping("/save")
    public ModelAndView save(MultipartFile file, String username) throws Exception{
        //把文件對象,以流的方式寫出到img的文件夾中
        String realpath = servletContext.getRealPath("/img");
        //創建保存到服務器的文件的路徑,使用時間戳改變文件名,以免重名
        String path= realpath +"/"+ new Date().getTime() + file.getOriginalFilename();
        File newFile = new File(path);
        file.transferTo(newFile);
        return null;
    }
}

文件下載

SpringMVC並沒有對文件下載做封裝,還是使用原來的方式

@Controller
public class DownLoadController {
    @Autowired
    private ServletContext context;

    @RequestMapping("/download")
    public ModelAndView download(String name, HttpServletRequest request,HttpServletResponse response) throws Exception{
        //GET請求中文件名為中文時亂碼處理
        name=new String(name.getBytes("ISO-8859-1"),"UTF-8");
        //設置響應頭為下載文件,而不是直接打開
        response.setContentType("application/x-msdownload");
        //獲取代理服務器信息,因為IE和其他瀏覽器的修改響應頭的中文格式的方式不同
        String userAgent=request.getHeader("User-Agent");
        if(userAgent.contains("IE")){
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(name,"UTF-8"));
        }else{
            response.setHeader("Content-Disposition","attachment;filename="+new String(name.getBytes("UTF-8"),"ISO-8859-1"));
        }
        //把文件對象,以流的方式寫出到img的文件夾中
        String realpath = context.getRealPath("/img");
        Files.copy(Paths.get(realpath,name),response.getOutputStream());
        return null;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM