//上传文件的控制层
//内容经供参考,以下代码是运行成功后的结果.切莫copy,拒绝只做理论帝,努力成为手工王,高手请留言,让大家一起学习进步,壮大我大中华程序员...
package com.YY.Upload.Servlet;
import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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;
import com.actionsoft.Util.CreateFileUtil;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = -7744625344830285257L;
private ServletContext sc;
private String savePath;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void init(ServletConfig config) {
// 在web.xml中设置的一个初始化参数
savePath = config.getInitParameter("savePath");
sc = config.getServletContext();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
int kb=(int) (item.getSize()/1024);
System.out.println("上传文件的大小:" + kb+"kb");
System.out.println("上传文件的类型:" + item.getContentType());
// item.getName()返回上传文件在客户端的完整路径名称
System.out.println("上传文件的名称:" + item.getName());
File tempFile = new File(item.getName());
//上传文件的保存路径
// String dirName = "E:/temp/SqlFile";
File dir = new File(sc.getRealPath("/") + savePath);
if(dir.exists()) {
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
}else{
CreateFileUtil.createDir(sc.getRealPath("/") + savePath);
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
}
request.setAttribute("upload.message", tempFile.getName()+"上传成功!"+kb+"kb");
}else{
request.setAttribute("upload.message", "没有选择上传文件!");
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
}
}