//需要将apache开发的两个插件包拷到lib目录下:commons-fileupload-1.2.2.jar commons-io-2.0.1.jar
package com.nay.servlet;
import java.io.File;
import java.io.IOException;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UpdateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");// 指定http响应的编码,同时指定了浏览器的显示编码。
request.setCharacterEncoding("utf-8");// 设置从request中取得的值编码格式。
// 创建一个DiskFileItemFactory工厂
FileItemFactory factory = new DiskFileItemFactory();
// 创建一个文件上传解析器
ServletFileUpload su = new ServletFileUpload(factory);
List<FileItem> list = null;
try {
// 解析器解析上传一个数据,并返回一个LIst<fileItem>集合,每一个FileItem对应一个Form表单的输入项。
list = su.parseRequest(request);
for (FileItem f : list) {
// 如果fileItem中封装的是普通输入项的数据
// 如果不是file域执行if中的命令,如果是file类的域执行else中
if (f.isFormField()) {
if (f.getFieldName().equals("username")) {
String username = f.getString("utf-8");
System.out.println(username);
}
} else {
// 如果是file类的域执行else
//得到需要上传到服务器文件夹的地址:F:\apache-tomcat-6.0.43-windows-i64\apache-tomcat-6.0.43\webapps\ROOT\file
String url = this.getServletContext().getRealPath("\\file");
//上传文件的文件名
String filename = f.getName();
// 获取文件的扩展名
String extName = filename.substring(filename
.lastIndexOf(".") + 1);
System.out.println(extName+"----------------------");
if (extName.equals("jpg") || extName.equals("gif")) {
//用上传地址的url地址新建一个文件夹
File ufile = new File(url);
//如果文件夹不存在,新建一个
if (!ufile.exists()) {
ufile.mkdir();
}
//新建一个文件,需要指定存放文件夹路径,和文件名
File file = new File(ufile, "flora.jpg");
f.write(file);
} else {
System.out
.println("please choose the right flie to update");
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}