81,092
社区成员
发帖
与我相关
我的任务
分享
下面是个例子,你可以看看:
servlet类:
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
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.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class Upload extends HttpServlet {
File fileDir;
File tempDir;
/**
* Constructor of the object.
*/
public Upload() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 让不同的请求做相同的事情
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024);
// 设置临时文件存储位置
factory.setRepository(tempDir);
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置单个文件的最大上传size
upload.setFileSizeMax(1024 * 1024);
// 设置整个request的最大size
upload.setSizeMax(1024 * 1024);
ProgressListener progressListener = new ProgressListener() {
private long megaBytes = -1;
public void update(long pBytesRead, long pContentLength, int pItems) {
long mBytes = pBytesRead / 1000;
if (megaBytes == mBytes) {
return;
}
megaBytes = mBytes;
System.out.println("We are currently reading item " + pItems);
if (pContentLength == -1) {
System.out.println("So far, " + pBytesRead
+ " bytes have been read.");
} else {
System.out.println("So far, " + pBytesRead + " of "
+ pContentLength + " bytes have been read.");
}
}
};
upload.setProgressListener(progressListener);
// Parse the request
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()) {
processFormField(item);
} else {
processUploadedFile(item);
}
}
} catch (Exception e) {
e.printStackTrace();
}
response.setContentType("text/html");
}
// Handle the field submitted from client
private void processFormField(FileItem item) {
String name = item.getFieldName();
String value = item.getString();
try {
System.out.println("[name]\t" + name + "\t[value]\t"
+ new String(value.getBytes("iso8859-1"), "gbk"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private String getFileName(String fileName) {
int index = fileName.lastIndexOf('\\');
if (index == -1) {
index = fileName.lastIndexOf('/');
}
if (index == -1) {
return fileName;
}
if (index == fileName.length() - 1) {
return fileName;
}
return fileName.substring(index + 1);
}
private void logInfo(Object o) {
System.out.println(o);
}
private void processUploadedFile(FileItem item) {
if (item.isFormField()) {
return;
}
String fieldName = item.getFieldName();
logInfo("[fieldName]\t" + fieldName);
String fileName = item.getName();
logInfo("[fileName]\t" + fileName);
String parsedFileName = getFileName(fileName);
logInfo("[parsedFileName]\t" + parsedFileName);
String contentType = item.getContentType();
logInfo("[contentType]\t" + contentType);
boolean isInMemory = item.isInMemory();
logInfo("[isInMemory]\t" + isInMemory);
long sizeInBytes = item.getSize();
logInfo("[sizeInBytes]\t" + sizeInBytes);
File uploadedFile = new File(fileDir, parsedFileName);
if (uploadedFile.exists()) {
// 如果文件同名做相应的处理
}
try {
item.write(uploadedFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// 得到当前目录
fileDir = new File(this.getServletContext().getRealPath("/")
+ "WEB-INF\\upload\\");
// 如果WEB-INF下upload文件夹不存在,就新建一个
if (!fileDir.exists()) {
fileDir.mkdir();
}
tempDir = new File(this.getServletContext().getRealPath("/")
+ "WEB-INF\\uploadTemp\\");
if (!tempDir.exists()) {
tempDir.mkdir();
}
}
}
jsp页面:
<form method="post" action="upload" name="fileuploadform" enctype="multipart/form-data">
<input type="file" name="file"></input>
<input type="submit"/>
</form>