1,所需jar包
commons-fileupload-1.3.3.jar,commons-io-1.4.jar
2,上传文件需要jsp表单中需要元素
<form action="LogoUploadServlet" enctype="multipart/form-data" method="post">
上传文件:<input type="file" name="file"><br/>
提交按钮: <input type="submit" value="提交" οnclick="reflash()" id="sub">
</form>
3,上传所需的servlet
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.dao.BookDao;
import com.yanqing.bean.Info;
import com.yanqing.dao.Site;
/**
* Servlet implementation class LogoUploadServlet
*/
@WebServlet("/LogoUploadServlet")
public class LogoUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LogoUploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload sfu=new ServletFileUpload(factory);
sfu.setFileSizeMax(1024*1024*1024);
sfu.setSizeMax(1024*1024*2000);
String urlname=null;
try {
List<FileItem> list=sfu.parseRequest(request);
//list0 中存放着表单中第一项元素,即图片。
FileItem file2=list.get(0);//上传的第一项
//文件保存路径
String root=this.getServletContext().getRealPath("/customerheadimg");
String filename=file2.getName();
//System.out.println("urlname"+urlname);
File dirFile=new File(root);
/*
* 创建目录链
* */
dirFile.mkdirs();
/*
* 创建目录文件
* */
File destFile=new File(dirFile,filename);
try {
file2.write(destFile);
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
//System.out.println("wenjianjia wenjian"+dirFile);
} catch (FileUploadException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}