javaweb--上傳檔案UploadServlet1.java

來源:互聯網
上載者:User

標籤:

package cn.itcast.web.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet1 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//request.getParameter("username"); //****錯誤
request.setCharacterEncoding("UTF-8"); //表單為檔案上傳,設定request編碼無效

//得到上傳檔案的儲存目錄
String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");

try{
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(this.getServletContext().getRealPath("/WEB-INF/temp")));

ServletFileUpload upload = new ServletFileUpload(factory);
/*upload.setProgressListener(new ProgressListener(){
public void update(long pBytesRead, long pContentLength, int arg2) {
System.out.println("檔案大小為:" + pContentLength + ",當前已處理:" + pBytesRead);
}
});*/

upload.setHeaderEncoding("UTF-8"); //解決上傳檔案名稱的中文亂碼

if(!upload.isMultipartContent(request)){
//按照傳統方式擷取資料
return;
}


/*upload.setFileSizeMax(1024);
upload.setSizeMax(1024*10);*/
List<FileItem> list = upload.parseRequest(request);
for(FileItem item : list){

if(item.isFormField()){
//fileitem中封裝的是普通輸入項的資料
String name = item.getFieldName();
String value = item.getString("UTF-8");
//value = new String(value.getBytes("iso8859-1"),"UTF-8");
System.out.println(name + "=" + value);
}else{
//fileitem中封裝的是上傳檔案
String filename = item.getName(); //不同的瀏覽器提交的檔案是不一樣 c:\a\b\1.txt 1.txt
System.out.println(filename);
if(filename==null || filename.trim().equals("")){
continue;
}
filename = filename.substring(filename.lastIndexOf("\\")+1);

InputStream in = item.getInputStream();
String saveFilename = makeFileName(filename); //得到檔案儲存的名稱

String realSavePath = makePath(saveFilename, savePath); //得到檔案的儲存目錄
FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename);
byte buffer[] = new byte[1024];
int len = 0;
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
}

in.close();
out.close();
item.delete(); //刪除臨時檔案

}

}

}catch (FileUploadBase.FileSizeLimitExceededException e) {
e.printStackTrace();
request.setAttribute("message", "檔案超出最大值!!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
catch (Exception e) {
e.printStackTrace();
}
}

public String makeFileName(String filename){ //2.jpg
return UUID.randomUUID().toString() + "_" + filename;
}

public String makePath(String filename,String savePath){

int hashcode = filename.hashCode();
int dir1 = hashcode&0xf; //0--15
int dir2 = (hashcode&0xf0)>>4; //0-15

String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5
File file = new File(dir);
if(!file.exists()){
file.mkdirs();
}         //產生目錄,並且把他建出來
return dir;
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}

 

 

//upload.jsp

 

 

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP ‘upload.jsp‘ starting page</title>
</head>

<body>

<form action="${pageContext.request.contextPath }/servlet/UploadServlet1" enctype="multipart/form-data" method="post">
上傳使用者:<input type="text" name="username"><br/>
上傳檔案1:<input type="file" name="file1"><br/>
上傳檔案2:<input type="file" name="file2"><br/>
<input type="submit" value="提交">
</form>

</body>
</html>

 

 

 

 

 

 

 

 

javaweb--上傳檔案UploadServlet1.java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.