Spring 實現檔案上傳與下載
阿新 • • 發佈:2019-01-27
檔案上傳
upload.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="/taglibs.jsp"%> <!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> <h2 > 檔案上傳 </h2> <div class="pageContent"> <form method="post" action="/dhcss/ssp/upload/upload.do" enctype="multipart/form-data"> <div class="pageFormContent nowrap" layoutH="97"> <input type="hidden" name="name" /> <input type="file" name="file"/> <div class="divider"></div> <p>自定義擴充套件請參照:dwz.validate.method.js</p> <p>錯誤提示資訊國際化請參照:dwz.regional.zh.js</p> </div> <div class="formBar"> <ul> <li><div class="buttonActive"> <div class="buttonContent"> <button type="submit">提交</button> </div> </div></li> <li><div class="button"> <div class="buttonContent"> <button type="button" class="close">取消</button> </div> </div></li> </ul> </div> </form> </div> </body> </html>
java 上傳程式碼;
package com.dhcc.dhcss.ssp.sm; import java.io.File; import java.util.Date; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; 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.context.ServletContextAware; import org.springframework.web.multipart.commons.CommonsMultipartFile; @Controller //宣告該類為控制器類 @RequestMapping("/ssp/upload") public class FileUploadController implements ServletContextAware{ //實現ServletContextAware介面,獲取本地路徑 private ServletContext servletContext; public void setServletContext(ServletContext servletContext) { //實現介面中的setServletContext方法 this.servletContext = servletContext; } @RequestMapping(value = "/upload", method = RequestMethod.POST) //將檔案上傳請求對映到該方法 public String handleFormUpload(@RequestParam("name") String name, //設定請求引數的名稱和型別 @RequestParam("file") CommonsMultipartFile mFile,HttpServletRequest req) { //請求引數一定要與form中的引數名對應 if (!mFile.isEmpty()) { //String path = this.servletContext.getRealPath("/"); //獲取本地儲存路徑 // String path="/home/chen/"; String pc=req.getServletContext().getRealPath("/WEB-INF/conf.properties"); Configuration rc = new Configuration(pc);//相對路徑 String path=rc.getValue("path"); System.out.println(path); //File file = new File(path + new Date().getTime() + ".jpg"); //新建一個檔案 File file = new File(path + new Date().getTime()); //新建一個檔案 System.out.println(file.getAbsolutePath()); try { mFile.getFileItem().write(file); //將上傳的檔案寫入新建的檔案中 } catch (Exception e) { e.printStackTrace(); } return "ssp/sm/uploadSuccess"; //返回成功檢視 }else { return "ssp/sm/uploadFail"; //返回失敗檢視 } } public void setServletContext1(ServletContext arg0) { // TODO Auto-generated method stub } }
uploadSuccess.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> <h3 align='center'><font color='red'>上傳成功,請去主資料夾下檢視~~</font></h3> <a href="http://localhost:8080/dhcss">返回首頁</a> </body> </html>
uploadFail.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>
<h3 align='center'><font color='red'>上傳失敗~~</font></h3>
<a href="http://localhost:8080/dhcss">返回首頁</a>
</body>
</html>
-------------------------------------------------------------------------------------------
download.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">
<script type="text/javascript" src="../../js/jquery-1.7.1.js"></script>
<title>upload</title>
</head>
<body>
<h2 >
檔案下載
</h2>
<div>
<div class="pageFormContent nowrap" layoutH="97">
請輸入資料夾下要下載的檔名(限英文名)
<input id='fileName' type="text" name="fileName" />
<div class="divider"></div>
<p>自定義擴充套件請參照:dwz.validate.method.js</p>
<p>錯誤提示資訊國際化請參照:dwz.regional.zh.js</p>
</div>
<div class="formBar">
<ul>
<li><div class="buttonActive">
<div class="buttonContent">
<a id="btn" href="/dhcss/download.do" target="blank"><button>下載</button></a>
</div>
</div></li>
<li><div class="button">
<div class="buttonContent">
<button type="button" class="close">取消</button>
</div>
</div></li>
</ul>
</div>
</div>
</body>
<script type="text/javascript">
$(function(){
$('a').click(function(){
var link=this.href+'?'+'fileName='+$('#fileName').val();
window.open(link);
return false;
});
});
</script>
</html>
java 檔案下載程式碼:
package com.dhcc.dhcss.ssp.sm;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class FileDownloadController {
//static final String dir = "/home/chen/";
@RequestMapping("download.do")
public void downloadFile(@RequestParam String fileName,HttpServletResponse response,HttpServletRequest req){
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
String pc=req.getServletContext().getRealPath("/WEB-INF/conf.properties");
Configuration rc = new Configuration(pc);//相對路徑
String dir=rc.getValue("path");
try {
File file=new File(dir+fileName);
System.out.println(file.getAbsolutePath());
InputStream inputStream=new FileInputStream(file);
OutputStream os=response.getOutputStream();
byte[] b=new byte[1024];
int length;
while((length=inputStream.read(b))>0){
os.write(b,0,length);
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}