日期:2014-05-17 浏览次数:20772 次
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.FileUploadException;
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 编码无效
*/
//得到上传文件的保存目录
try {
String savePath=this.getServletContext().getRealPath("/WEB-INF/upload");
System.out.println("文件上传的保存路径为:" + savePath);
DiskFileItemFactory factory=new DiskFileItemFactory();
factory.setRepository(new File(this.getServletContext().getRealPath("/WEB-INF/temp")));//设置临时文件路径
ServletFileUpload upload=new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");//解决上传文件名的中文乱码问题
if(!upload.isMultipartContent(request)){
//按照传统方式获取数据
return;
}
List<FileItem> list=upload.parseRequest(request);
for(FileItem item:list){
if(item.isFormField()){
//fileitem中封装的是普通输入项的数据
String name=item.getFieldName();
System.out.println("字段名是:" + name);
String value=item.getString("utf-8");
System.out.println("字段值是:" + value);
}else{
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);//获取文件名称
String saveFilename=makeFileName(filename);//设定保存的文件名称
InputStream in=item.getInputStream();
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 (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String makePath(String saveFil