<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/shang" enctype="multipart/form-data" method="post">
<input type="file" name="file">上传文件
<input type="submit" value="提交">
</form>
$END$
</body>
</html>
package com.xiang;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
public class shang extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(!ServletFileUpload.isMultipartContent(request))
{
return;
}
String uploadPath = this.getServletContext().getRealPath("WEB-INF/shang");
File uploadFile =new File(uploadPath);
if (!uploadFile.exists()) {
uploadFile.mkdir();
}
String tmpPath = this.getServletContext().getRealPath("WEB-INF/tmp");
File tmpFile =new File(tmpPath);
if (!tmpFile.exists()) {
tmpFile.mkdir();
}
DiskFileItemFactory factory=new DiskFileItemFactory();
factory.setRepository(tmpFile);
ServletFileUpload upload=new ServletFileUpload(factory);
upload.setProgressListener(new ProgressListener() {
@Override
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("总大小" +pContentLength+"已上传"+pBytesRead);
}
});
System.out.println(11111);
List<FileItem> fileItems=null;
try {
fileItems=upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
System.out.println(2222);
System.out.println(fileItems.get(0).getFieldName());
for (FileItem f :
fileItems) {
if (f.isFormField())
{
String name=f.getFieldName();
String value =f.getString("utf-8");
System.out.println(name+":"+value);
}
else {
System.out.println(333);
String name=f.getFieldName();
if (name.trim().equals("")||name==null)
{
continue;
}
String fileName=name.substring(name.lastIndexOf("/")+1);
String fileExtname=name.substring(name.lastIndexOf(".")+1);
UUID uuid = UUID.randomUUID();
String realpath=uploadPath+"/"+uuid;
File realPathFile=new File(realpath);
if (!realPathFile.exists())
realPathFile.mkdir();
InputStream inputStream=f.getInputStream();
System.out.println(inputStream==null);
FileOutputStream fos=new FileOutputStream(realpath+"/"+name);
byte[] buff=new byte[1024*1024];
int len=0;
while ((len=inputStream.read())>0)
{
fos.write(buff,0,len);
}
fos.close();
inputStream.close();
String msg="文件上传成功";
System.out.println(msg);
f.delete();
}
}
}
}