jsp和servlet實現檔案的上傳和下載
阿新 • • 發佈:2020-09-09
一、專案資料夾和所需jar包
二、檔案上傳:
index.jsp 檔案程式碼:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>File upload</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/Upload" enctype="multipart/form-data" method="post">
上傳使用者:<input type="text" name="username"><br/><br/>
上傳檔案1:<input type="file" name="file1"><br/><br/>
上傳檔案2:<input type="file" name="file2"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
Upload.java檔案程式碼:
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
@WebServlet("/Upload")
public class Upload extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//得到上傳檔案的儲存目錄,將上傳的檔案存放在WEB-INF目錄下面 不允許外界直接訪問,保證上傳檔案的安全性
String savePath = this.getServletContext().getRealPath("WEB-INF/file");
System.out.println(savePath);
req.setCharacterEncoding("utf-8");
File file =new File(savePath);
if(!file.exists()&&!file.isDirectory()){ //判斷路徑是否存在,路徑不存在則建立路徑
System.out.println(savePath+"目標目錄不存在,需要進行建立");
file.mkdir();
}
String message = null;
try {
//1 建立DiskFileItemFactory工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
//2 建立一個檔案上傳解析器
ServletFileUpload upload = new ServletFileUpload(factory);
//判斷提交上來的資料是不是表單上的資料
upload.setHeaderEncoding("UTF-8");
boolean mt = ServletFileUpload.isMultipartContent(req);
System.out.println(mt);
if (!ServletFileUpload.isMultipartContent(req)) {
System.out.println("非表單資料!");
return;
}
//4 使用ServletFileUpload解析器來解析上傳資料,解析結果返回的是一個List<FileItem>
//集合,每一個FileItem對應一個Form表單的輸入項
List<FileItem> list = upload.parseRequest(req);
for(FileItem item:list) {
if (item.isFormField()) { //如果表單中有普通型別便籤則為true
String name = item.getFieldName(); //獲取表單中普通標籤的name屬性
String value = item.getString("UTF-8");
System.out.println(name + "=" + value);
} else {
String filename = item.getName();
System.out.println(filename);
if (filename == null || filename.trim().equals("")) {
continue;
}
//注意:不同的瀏覽器提交的檔名是不一樣的,有些瀏覽器提交上來的檔名是帶有路徑的,
如: c:\a\b\1.txt,而有些只是單純的檔名,如:1.txt
//處理獲取到的上傳檔案的檔名的路徑部分,只保留檔名部分
filename = filename.substring(filename.lastIndexOf("\\") + 1);
//獲取item輸入流
InputStream inputStream = item.getInputStream();
//建立一個檔案輸出流
FileOutputStream fileOutputStream =new FileOutputStream(savePath+"\\"+filename);
//建立一個緩衝區
byte buffer[] = new byte[1024];
//判斷輸入流是否已經讀完的標識
int len = 0;
while ((len=inputStream.read(buffer))>0)
{
fileOutputStream.write(buffer,0,len);
}
inputStream.close();
fileOutputStream.close();
item.delete();
message = "檔案上傳成功";
}
}
}catch (Exception e)
{
message = "檔案上傳失敗";
e.printStackTrace();
}
req.setAttribute("message",message);
req.getRequestDispatcher("WEB-INF/message.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
頁面提交上傳檔案:
上傳成功:
三、檔案下載:
<%--
Created by IntelliJ IDEA.
User: ibear
Date: 2020/9/9
Time: 15:25
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script>
function doDownload()
{
var fileName = "C:\\Users\\ibear\\Desktop\\Java\\upload\\web\\WEB-INF\\lib\\";
var filePath = "commons-fileupload-1.4.jar";
return window.location.href=encodeURI("./docdownload.jsp?fName="+
encodeURIComponent(fileName)+"&fPath="+encodeURIComponent(filePath));
}
</script>
</head>
<body>
<a href="javascript:doDownload()" style="color: dodgerblue"><u>下載</u></a>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: ibear
Date: 2020/9/9
Time: 15:31
To change this template use File | Settings | File Templates.
--%>
<%@page language="java" contentType="application/x-msdownload" import="java.io.*,java.net.*,java.util.Locale" pageEncoding="UTF-8"%>
<%
//關於檔案下載時採用檔案流輸出的方式處理:
//加上response.reset(),並且所有的%>後面不要換行,包括最後一個;
//因為Application Server在處理編譯jsp時對於%>和<%之間的內容一般是原樣輸出,而且預設是PrintWriter,
//而你卻要進行流輸出:ServletOutputStream,這樣做相當於試圖在Servlet中使用兩種輸出機制,
//就會發生:getOutputStream() has already been called for this response的錯誤
//詳細請見《More Java Pitfill》一書的第二部分 Web層Item 33:試圖在Servlet中使用兩種輸出機制 270
//而且如果有換行,對於文字檔案沒有什麼問題,但是對於其它格式,比如AutoCAD、Word、Excel等檔案
//下載下來的檔案中就會多出一些換行符0x0d和0x0a,這樣可能導致某些格式的檔案無法開啟,有些也可以正常開啟。
response.reset();//可以加也可以不加
response.setContentType("application/x-download");//設定為下載application/x-download
// /../../退WEB-INF/classes兩級到應用的根目錄下去,注意Tomcat與WebLogic下面這一句得到的路徑不同,WebLogic中路徑最後沒有/
String fName = request.getParameter("fName");
String fPath = request.getParameter("fPath");
String filenamedownload = fPath;//需要下載的檔案
String filenamedisplay = fName;//預設儲存檔名
filenamedownload = URLDecoder.decode(fName,"utf-8");
filenamedisplay = URLDecoder.decode(fPath,"utf-8");
//處理由於AIX上中文變亂碼,導致判斷檔案是否存在不準確
String osName = System.getProperty("os.name");
if("AIX".equals(osName.toUpperCase(Locale.ENGLISH))){
try {
filenamedownload = new String(filenamedownload.getBytes("GBK"),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
}
}
response.addHeader("Content-Disposition", "attachment;filename=" +
new String((filenamedisplay).getBytes("GBK"), "ISO8859-1"));
OutputStream output = null;
FileInputStream fis = null;
try {
output = response.getOutputStream();
fis = new FileInputStream(filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while ((i = fis.read(b)) > 0) {
output.write(b, 0, i);
}
output.flush();
if (output != null) {
output.close();
output = null;
}
}catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
fis = null;
}
if (output != null) {
output.close();
output = null;
}
}
%>
下載成功:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>File upload</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/Upload" enctype="multipart/form-data" method="post">
上傳使用者:<input type="text" name="username"><br/><br/>
上傳檔案1:<input type="file" name="file1"><br/><br/>
上傳檔案2:<input type="file" name="file2"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>