fileUpload.java
/**
*需要commons-fileupload-1.3.jar和commons-io-1.2.jar
*/
public class fileUpload extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8"); // 設置編碼
String fName = "";
String suffix = "";
// 獲得磁盤文件條目工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
// 獲取文件需要上傳到的路徑
// String path = request.getRealPath("/upload1");//該方法已經被淘汰
String path = this.getServletContext().getRealPath("/upload1");
// String path = "c:/upload1";
// 如果沒以下兩行設置的話,上傳大的 文件 會占用 很多內存,
// 設置暫時存放的 存儲室 , 這個存儲室,可以和 最終存儲文件 的目錄不同
/**
* 原理 它是先存到 暫時存儲室,然后在真正寫到 對應目錄的硬盤上, 按理來說 當上傳一個文件時,其實是上傳了兩份,第一個是以 .tem
* 格式的 然后再將其真正寫到 對應目錄的硬盤上
*/
factory.setRepository(new File(path));
// 設置 緩存的大小,當上傳文件的容量超過該緩存時,直接放到 暫時存儲室
factory.setSizeThreshold(1024 * 1024);
// 高水平的API文件上傳處理
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// 可以上傳多個文件
List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
for (FileItem item : list) {
// 獲取表單的屬性名字
String name = item.getFieldName();
// 如果獲取的 表單信息是普通的 文本 信息
if (item.isFormField()) {
// 獲取用戶具體輸入的字符串 ,名字起得挺好,因為表單提交過來的是 字符串類型的
String value = item.getString();
request.setAttribute(name, value);
} else {// 對傳入的非 簡單的字符串進行處理 ,比如說二進制的 圖片,電影這些
/**
* 以下三步,主要獲取 上傳文件的名字
*/
// 獲取路徑名
String value = item.getName();
// 索引到最后一個反斜杠
int start = value.lastIndexOf("\\");
// 截取 上傳文件的 字符串名字,加1是 去掉反斜杠,
String filename = value.substring(start + 1);
// 真正寫到磁盤上
// 它拋出的異常 用exception 捕捉
// item.write( new File(path,filename) );//第三方提供的
// 手動寫入的
// 如果有文件名
if (filename.indexOf(".") >= 0) {
// 就截取.之前的字符串
int indexdot = filename.indexOf(".");
suffix = filename.substring(indexdot);
fName = filename
.substring(0, filename.lastIndexOf("."));
Date now = new Date();
fName = fName + "_" + now.getTime();
fName = fName + suffix;
}
OutputStream out = new FileOutputStream(new File(path,
fName));
request.setAttribute(name, fName);
InputStream in = item.getInputStream();
int length = 0;
byte[] buf = new byte[1024];
System.out.println("獲取上傳文件的總共的容量:" + item.getSize());
// in.read(buf) 每次讀到的數據存放在 buf 數組中
while ((length = in.read(buf)) != -1) {
// 在 buf 數組中 取出數據 寫到 (輸出流)磁盤上
out.write(buf, 0, length);
}
in.close();
out.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
request.getRequestDispatcher("filedemo.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
index.jsp
/**
* 需要jquery-3.1.1.min.js
*/
<%@ 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>上傳入口</title>
<script src="./js/jquery-3.1.1.min.js"></script>
</head>
<body>
<form action="fileUpload" enctype="multipart/form-data" method="post">
用戶名稱:<input type="text" name="usename"> <br />
上傳圖片:<input type="file" id="file0" name="file1"><br />
<img src="" id="img0"><br/>
<!-- 上傳文件:<input type="file" name="file2"><br /> -->
<input type="submit" value="提交" />
</form>
<script>
$("#file0").change(function() {
var objUrl = getObjectURL(this.files[0]);
console.log("objUrl = " + objUrl);
if (objUrl) {
$("#img0").attr("src", objUrl);
}
});
//建立一個可存取到該file的url
function getObjectURL(file) {
var url = null;
if (window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
}
</script>
</body>
</html>
filedemo.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>上傳文件圖片案列</title>
</head>
<body>
用戶名稱:${requestScope.usename }<br />
圖片名稱:${requestScope.file1 }<br />
<%-- 文件名稱:${requestScope.file2 }<br /> --%>
<!-- 把上傳的圖片顯示出來 -->
<img alt="go" src="upload1/<%=(String) request.getAttribute("file1")%> " />
</body>
</html>