javaweb--上传文件UploadServlet1.java

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

上一篇:ZooKeeper与Curator注册和监控


下一篇:SpringMVC控制器配置文件