本文實(shí)例講述了servlet+JSP+mysql實(shí)現(xiàn)文件上傳的方法。分享給大家供大家參考,具體如下:
一、文件上傳的基本操作:
1、 表單屬性enctype的設(shè)置
multipart/form-data和application/x-www-form-urlencoded的區(qū)別
FORM元素的enctype屬性指定了表單數(shù)據(jù)向服務(wù)器提交時(shí)所采用的編碼類型,默認(rèn)的缺省值是“application/x-www-form-urlencoded”。
然而,在向服務(wù)器發(fā)送大量的文本、包含非ASCII字符的文本或二進(jìn)制數(shù)據(jù)時(shí)這種編碼方式效率很低。
在文件上載時(shí),所使用的編碼類型應(yīng)當(dāng)是“multipart/form-data”,它既可以發(fā)送文本數(shù)據(jù),也支持二進(jìn)制數(shù)據(jù)上載。
Browser端form>表單的ENCTYPE屬性值為multipart/form-data,它告訴我們傳輸?shù)臄?shù)據(jù)要用到多媒體傳輸協(xié)議,由于多媒體傳輸?shù)亩际谴罅康臄?shù)據(jù),所以規(guī)定上傳文件必須是post方法,input>的type屬性必須是file。
實(shí)現(xiàn)過程:
package cn.csdn.web.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import cn.csdn.web.c3p0.DBManager_c3p0;
public class Upload2Servlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
try {
//實(shí)例化一個(gè)文件工廠
DiskFileItemFactory factory=new DiskFileItemFactory();
factory.setRepository(new File("C:\\osp"));
String paramName=null;
String paramValue=null;
//配置上傳組件ServletFileUpload
ServletFileUpload upload=new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
upload.setFileSizeMax(1024*1024);
//從request得到所有上傳域的列表
ListFileItem> list=upload.parseRequest(request);
for(FileItem item:list){
//如果是上傳域的文件域
if(item.isFormField()){
//表單普通輸入項(xiàng)
paramName = item.getFieldName(); //上傳于的Name
// String paramValue=item.getString();
// paramValue=new String(paramValue.getBytes("iso8859-1"),"UTF-8");
paramValue=item.getString("UTF-8");
System.out.println(paramName+"="+paramValue);
}else{
//上傳文件處理
String fileName = item.getName();
fileName=fileName.substring(fileName.lastIndexOf("\\")+1); //截取擴(kuò)展名
System.out.println("name="+fileName);
if(!fileName.equals("")){
// fileName=refactorFileName(fileName);
InputStream in=item.getInputStream();
File file = new File("c:\\"+fileName);
FileOutputStream os=new FileOutputStream(file);
byte[] buf = new byte[1024];
int len=0;
while((len=in.read(buf))>0){
os.write(buf,0,len);
}
os.flush();
os.close();
in.close();
item.delete();
request.setAttribute("message", "文件上傳成功");
try {
DataSource ds = DBManager_c3p0.getDataSource();
QueryRunner runner = new QueryRunner(ds);
String sql = "insert into user(name,file) values(?,?)";
Object[] params = {paramValue,fileName};
runner.update(sql, params);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch(FileSizeLimitExceededException e1){
e1.printStackTrace();
request.setAttribute("message", "文件尺寸太大");
}catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
request.setAttribute("message", "文件上傳失敗");
}
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
// public String refactorFileName(String fileName){
// return UUID.randomUUID().toString()+"_"+fileName;
// }
}
二、上傳文件要注意的有:
注意編碼問題 防止出現(xiàn)中文亂碼 上邊列舉出一種
其他的還有臨時(shí)文件解決問題 臨時(shí)文件刪除問題
解決沒有指定文件名的問題
判斷獲取的文件名是否為空
保存路徑問題
如表示url資源時(shí)應(yīng)該用斜杠 “/”
如表示硬盤路徑時(shí)用斜杠“\\”
為保證服務(wù)器安全,上傳的文件應(yīng)禁止用戶直接訪問,通常保存在應(yīng)用程序的WEB-INF目錄下,或者不受WEB服務(wù)器管理的目錄
希望本文所述對(duì)大家jsp程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- Jsp頁(yè)面實(shí)現(xiàn)文件上傳下載類代碼
- jsp中點(diǎn)擊圖片彈出文件上傳界面及預(yù)覽功能的實(shí)現(xiàn)
- jsp實(shí)現(xiàn)文件上傳下載的程序示例
- Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件上傳(一)
- AJAX和JSP實(shí)現(xiàn)的基于WEB的文件上傳的進(jìn)度控制代碼
- jsp文件上傳與下載實(shí)例代碼
- jsp中點(diǎn)擊圖片彈出文件上傳界面及實(shí)現(xiàn)預(yù)覽實(shí)例詳解
- 利用jsp+Extjs實(shí)現(xiàn)動(dòng)態(tài)顯示文件上傳進(jìn)度
- jsp 文件上傳瀏覽,支持ie6,ie7,ie8
- JSP實(shí)現(xiàn)文件上傳功能