<span style="font-family:Microsoft YaHei;font-size:18px;background-color: rgb(204, 204, 204);">
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class CoreServlet
*/
@WebServlet(asyncSupported = true, urlPatterns = { "/CoreServlet" })
public class CoreServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CoreServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
//獲得磁盤文件條目工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
//獲取文件需要上傳到的路徑
String path = this.getServletContext().getRealPath("/temp");
//如果沒以下兩行設置的話,上傳大的 文件 會佔用 很多內存,
//設置暫時存放的 存儲室 , 這個存儲室,可以和 最終存儲文件 的目錄不同
/**
* 原理 它是先存到 暫時存儲室,然後在真正寫到 對應目錄的硬盤上,
* 按理來說 當上傳一個文件時,其實是上傳了兩份,第一個是以 .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);
request.setAttribute(name, filename);
//真正寫到磁盤上
//它拋出的異常 用exception 捕捉
//item.write( new File(path,filename) );//第三方提供的
//手動寫的
OutputStream out = new FileOutputStream(new File(path,filename));
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();
response.getWriter().write("{'success':true}");
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
response.getWriter().write("捕捉到異常:" + e.getMessage());
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
response.getWriter().write("捕捉到異常:" + e.getMessage());
e.printStackTrace();
//e.printStackTrace();
}
}
}
</span>
<span style="font-family:Microsoft YaHei;font-size:18px;background-color: rgb(204, 204, 204);">以上部分爲後臺代碼,需要兩個jar包,commons-fileupload,commons-io</span>
<span style="font-family:Microsoft YaHei;font-size:18px;background-color: rgb(204, 204, 204);">-----------------------------------------------------------------這個不是分割線-------------------------------------------------------------------</span>
<span style="font-family:Microsoft YaHei;font-size:18px;background-color: rgb(204, 204, 204);">以下是前端頁面代碼</span>
<span style="font-family:Microsoft YaHei;font-size:18px;background-color: rgb(204, 204, 204);">
</span>
<pre name="code" class="html"><span style="font-family:Microsoft YaHei;font-size:18px;background-color: rgb(204, 204, 204);"><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>上傳文件</title>
<script type="text/javascript">
function uploadFile() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('myDiv').innerHTML=xmlhttp.responseText;
}
}
var formdata = new FormData(document.getElementById('form1'));
xmlhttp.open("POST", "./CoreServlet", true);
xmlhttp.send(formdata);
}
</script>
</head>
<body>
<form id="form1" enctype="multipart/form-data">
選擇要上傳的文件:<input type="file" name="file" /><br>
<button type="button" onclick="uploadFile()">發送</button>
</form>
<br>
<div id="myDiv"><h2></h2></div>
</body>
</html></span>
<span style="font-family:Microsoft YaHei;font-size:18px;background-color: rgb(204, 204, 204);">
</span>
<span style="font-family:Microsoft YaHei;font-size:18px;background-color: rgb(204, 204, 204);">
</span>
<span style="font-family:Microsoft YaHei;font-size:18px;background-color: rgb(204, 204, 204);">
</span>
<span style="font-family:Microsoft YaHei;font-size:18px;background-color: rgb(204, 204, 204);">
</span>
<span style="font-family:Microsoft YaHei;font-size:18px;background-color: rgb(204, 204, 204);">
</span>
<span style="font-family:Microsoft YaHei;font-size:18px;background-color: rgb(204, 204, 204);">
</span>
<span style="font-family:Microsoft YaHei;font-size:18px;background-color: rgb(204, 204, 204);">
</span>