SpringMVC 實現文件的上傳與下載


一  配置SpringMVC ,並導入與文件上傳下載有關的jar包(在此不再贅述)

二 新建 相應 jsp 和controller

FileUpAndDown.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/fileUpLoad" method="post"  enctype="multipart/form-data">
文件名<input type="file" name="photo"/><br/>
     <input type="text" name="desc"/> <br/>
     <input type="submit" value="提交"/><br/>
</form>
<h3>童話鎮.mp3  陳一發兒</h3>
<a href="${pageContext.request.contextPath}/fileDownLoad">前去下載</a>
</body>
</html>

package
com.neuedu.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.commons.CommonsMultipartFile; @Controller public class FileUpAndDown { @RequestMapping(value="/fileUpLoad") public String testUpload(HttpServletRequest request,@RequestParam(value="desc",required=false) String desc,@RequestParam("photo") CommonsMultipartFile file) throws Exception{ ServletContext servletContext = request.getServletContext();//獲取ServletContext的對象 代表當前WEB應用 String realPath = servletContext.getRealPath("/uploads");//得到文件上傳目的位置的真實路徑 System.out.println("realPath :"+realPath); File file1 = new File(realPath); if(!file1.exists()){ file1.mkdir(); //如果該目錄不存在,就創建此抽象路徑名指定的目錄。 } String prefix = UUID.randomUUID().toString(); prefix = prefix.replace("-",""); String fileName = prefix+"_"+file.getOriginalFilename();//使用UUID加前綴命名文件,防止名字重復被覆蓋 InputStream in= file.getInputStream();;//聲明輸入輸出流 OutputStream out=new FileOutputStream(new File(realPath+"\\"+fileName));//指定輸出流的位置; byte []buffer =new byte[1024]; int len=0; while((len=in.read(buffer))!=-1){ out.write(buffer, 0, len); out.flush(); //類似於文件復制,將文件存儲到輸入流,再通過輸出流寫入到上傳位置 } //這段代碼也可以用IOUtils.copy(in, out)工具類的copy方法完成 out.close(); in.close(); return "success"; } @RequestMapping("/fileDownLoad") public ResponseEntity<byte[]> fileDownLoad(HttpServletRequest request) throws Exception{ ServletContext servletContext = request.getServletContext(); String fileName="童話鎮.mp3"; String realPath = servletContext.getRealPath("/WEB-INF/"+fileName);//得到文件所在位置 InputStream in=new FileInputStream(new File(realPath));//將該文件加入到輸入流之中 byte[] body=null; body=new byte[in.available()];// 返回下一次對此輸入流調用的方法可以不受阻塞地從此輸入流讀取(或跳過)的估計剩余字節數 in.read(body);//讀入到輸入流里面 fileName=new String(fileName.getBytes("gbk"),"iso8859-1");//防止中文亂碼 HttpHeaders headers=new HttpHeaders();//設置響應頭 headers.add("Content-Disposition", "attachment;filename="+fileName); HttpStatus statusCode = HttpStatus.OK;//設置響應嗎 ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode); return response; //public ResponseEntity(T body, // MultiValueMap < String,String > headers, // HttpStatus statusCode) //HttpEntity使用給定的正文,標題和狀態代碼創建一個新的。 //參數: //body - 實體機構 //headers - 實體頭 //statusCode - 狀態碼 } }

JSP界面:

 

上傳文件:

上傳文件目的位置:E:\“eclipse工作目錄“”\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\“項目名”\upload

為了好找需要配置一個eclipse插件 如何安裝地址:http://blog.csdn.net/a332056918/article/details/76180530

安裝成功后

在eclipse下方找到Servers,右鍵點擊即可出現如下頁面,再點擊Browse Deployment Location...即可跳到項目所在目錄--點擊項目名稱即可看見 你所上傳的文件夾

下載文件:

要下載的文件所在位置:

 


免責聲明!

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



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