ajax jsp 無重新整理上傳檔案,ajaxjsp
本文實現的檔案上傳也是無頁面重新整理的,可以說是一種"類似AJAX"方法
開始之前先說兩句無關的,其實在ajax出現之前,web應用也可以是無重新整理的,那時大多通過IFrame來做到這一點。當然Ajax出現之後,人們一窩蜂地投奔Ajax 的陣營了,iFrame 就乏人問津了。但是用iFrame來實現無重新整理上傳檔案確實一個很好的選擇。
ps:Ajax技術基本上可以說是由google公司帶起來的,但少Gmail中上傳檔案用的還是 IFrame,所以使用IFrame來上傳檔案是最好的選擇。
我在這裡這裡用的技術是jsp,其實asp,php等也是一樣可以這麼實現的
html:
<html>
<body>
<form action="/FileUploadServlet" id="form1" name="form1" encType="multipart/form-data" method="post" target="hidden_frame" >
<input type="file" id="file" name="file" style="width:450">
<INPUT type="submit" value="上傳檔案"><span id="msg"></span>
<br>
<font color="red">支援JPG,JPEG,GIF,BMP,SWF,RMVB,RM,AVI檔案的上傳</font>
<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
</form>
</body>
</html>
<script type="text/javascript">
function callback(msg)
{
document.getElementById("file").outerHTML = document.getElementById("file").outerHTML;
document.getElementById("msg").innerHTML = "<font color=red>"+msg+"</font>";
}
</script>
java 邏輯處理:
package com.partner.servlets;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
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;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.partner.core.util.UploadConfigurationRead;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected final transient Log log = LogFactory.getLog(FileUploadServlet.class);
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response){
//檔案存放的目錄
//File tempDirPath =new File(request.getSession().getServletContext().getRealPath("/")+File.separator+"uploads");
String path = UploadConfigurationRead.getInstance().getConfigItem("tempPath").trim();
File tempDirPath = new File(path);
if(!tempDirPath.exists()){
tempDirPath.mkdirs();
}
//建立磁碟檔案工廠
DiskFileItemFactory fac = new DiskFileItemFactory();
//建立servlet檔案上傳組件
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("UTF-8");
//檔案清單
List fileList = null;
//解析request從而得到前台傳過來的檔案
try {
fileList = upload.parseRequest(request);
} catch (FileUploadException ex) {
ex.printStackTrace();
return;
}
//儲存後的檔案名稱
String imageName = null;
//便利從前台得到的檔案清單
Iterator<FileItem> it = fileList.iterator();
while(it.hasNext()){
FileItem item = it.next();
//如果不是普通表單域,當做檔案域來處理
BufferedInputStream in = null;
BufferedOutputStream out = null;
if(!item.isFormField()){
imageName = new Date().getTime()+"_"+item.getName();
try {
in = new BufferedInputStream(item.getInputStream());
out = new BufferedOutputStream(
new FileOutputStream(new File(tempDirPath+File.separator+imageName)));
Streams.copy(in, out, true);
} catch (IOException e) {
log.error("檔案上傳異常:", e);
}finally{
if(in != null){
try {
in.close();
} catch (IOException e) {
log.error("上傳檔案關閉輸入失敗",e);
}
}
if(out != null){
try {
out.close();
} catch (IOException e) {
log.error("上傳檔案關閉輸出失敗",e);
}
}
}
}
}
PrintWriter out = null;
try {
out = encodehead(request, response);
} catch (IOException e) {
e.printStackTrace();
}
//這個地方不能少,否則前台得不到上傳的結果
out.write("<script>parent.callback('upload file success')</script>);
out.write(imageName);
out.close();
}
/**
* Ajax輔助方法 擷取 PrintWriter
* @return
* @throws IOException
* @throws IOException
* request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
*/
private PrintWriter encodehead(HttpServletRequest request,HttpServletResponse response) throws IOException{
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
return response.getWriter();
}
}