需要导入两个jar包:fileupload.jar、io.jar
test.html
<form method="post" action="ImgServlet" enctype="multipart/form-data" name="uploadform">
照片:<input type="file" name="uploadfile">
<input type="submit" value="上传" class="bt">
<span class="tfont">(为商品添加图片)只能上传 *.jpg , *.gif</span>
</form>
ImgServlet
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
public class AddProImgServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public AddProImgServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String imageUrl = null;
// 图片上传路径
String uploadPath = request.getRealPath("/") + "products/";
// 图下临时上传路径
String tempPath = request.getRealPath("/") + "products/temp/";
// 数据库中图片网络相对路径
String imagePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/";
// 数据库中图片网络URL
// 文件夹不存在就自动创建:
if (!new File(uploadPath).isDirectory())
new File(uploadPath).mkdirs();
if (!new File(tempPath).isDirectory())
new File(tempPath).mkdirs();
try {
DiskFileUpload fu = new DiskFileUpload();
// 设置最大文件尺寸,这里是4MB
fu.setSizeMax(4194304);
// 设置缓冲区大小,这里是4kb
fu.setSizeThreshold(4096);
// 设置临时目录:
fu.setRepositoryPath(tempPath);
// 得到所有的文件:
List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
// 依次处理每一个文件:
while (i.hasNext()) {
FileItem file = (FileItem) i.next();
// 获得文件名,这个文件名是用户上传时用户的绝对路径:
String fileName = file.getName();
// 看文件以什么结束
// System.out.println(fileName.endsWith(".gif"));
if (fileName != null
&& (fileName.endsWith(".jpg")
|| fileName.endsWith(".gif") || fileName
.endsWith(".doc"))) {
// 在这里可以记录用户和文件信息
// 生成上传后的文件名
String filename = null;
Random rd = new Random();
Calendar time = Calendar.getInstance();
if (fileName.endsWith(".jpg")) {
filename = String.valueOf(time.get(Calendar.YEAR))
+ String.valueOf(time.get(Calendar.MONTH))
+ String.valueOf(time
.get(Calendar.DAY_OF_MONTH))
+ String
.valueOf(time.get(Calendar.HOUR_OF_DAY))
+ String.valueOf(time.get(Calendar.MINUTE))
+ String.valueOf(time.get(Calendar.SECOND))
+ String.valueOf(rd.nextInt(100)) + ".jpg";
} else if (fileName.endsWith(".gif")) {
filename = String.valueOf(time.get(Calendar.YEAR))
+ String.valueOf(time.get(Calendar.MONTH))
+ String.valueOf(time
.get(Calendar.DAY_OF_MONTH))
+ String
.valueOf(time.get(Calendar.HOUR_OF_DAY))
+ String.valueOf(time.get(Calendar.MINUTE))
+ String.valueOf(time.get(Calendar.SECOND))
+ String.valueOf(rd.nextInt(100)) + ".gif";
}
File f1 = new File(uploadPath + filename);
// 打印相对路径
// System.out.print(f1.getAbsolutePath());
// 数据库中存储图片路径为:
// http://127.0.0.1:8080/MailSend/upload/images/1.jpg
// 要写入数据库的路径 imageUrl
file.write(f1);
imageUrl = imagePath + "products/" + filename;
if(flag){
//成功后跳转到主面
response.sendRedirect("index.jsp");
}
else {
response.sendRedirect("error.jsp"); //失败后跳转到错误页
}
}
}
// 跳转到上传成功提示页面
} catch (Exception e) {
// 可以跳转出错页面
}
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}
test.html
<form method="post" action="ImgServlet" enctype="multipart/form-data" name="uploadform">
照片:<input type="file" name="uploadfile">
<input type="submit" value="上传" class="bt">
<span class="tfont">(为商品添加图片)只能上传 *.jpg , *.gif</span>
</form>
ImgServlet
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
public class AddProImgServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public AddProImgServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String imageUrl = null;
// 图片上传路径
String uploadPath = request.getRealPath("/") + "products/";
// 图下临时上传路径
String tempPath = request.getRealPath("/") + "products/temp/";
// 数据库中图片网络相对路径
String imagePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/";
// 数据库中图片网络URL
// 文件夹不存在就自动创建:
if (!new File(uploadPath).isDirectory())
new File(uploadPath).mkdirs();
if (!new File(tempPath).isDirectory())
new File(tempPath).mkdirs();
try {
DiskFileUpload fu = new DiskFileUpload();
// 设置最大文件尺寸,这里是4MB
fu.setSizeMax(4194304);
// 设置缓冲区大小,这里是4kb
fu.setSizeThreshold(4096);
// 设置临时目录:
fu.setRepositoryPath(tempPath);
// 得到所有的文件:
List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
// 依次处理每一个文件:
while (i.hasNext()) {
FileItem file = (FileItem) i.next();
// 获得文件名,这个文件名是用户上传时用户的绝对路径:
String fileName = file.getName();
// 看文件以什么结束
// System.out.println(fileName.endsWith(".gif"));
if (fileName != null
&& (fileName.endsWith(".jpg")
|| fileName.endsWith(".gif") || fileName
.endsWith(".doc"))) {
// 在这里可以记录用户和文件信息
// 生成上传后的文件名
String filename = null;
Random rd = new Random();
Calendar time = Calendar.getInstance();
if (fileName.endsWith(".jpg")) {
filename = String.valueOf(time.get(Calendar.YEAR))
+ String.valueOf(time.get(Calendar.MONTH))
+ String.valueOf(time
.get(Calendar.DAY_OF_MONTH))
+ String
.valueOf(time.get(Calendar.HOUR_OF_DAY))
+ String.valueOf(time.get(Calendar.MINUTE))
+ String.valueOf(time.get(Calendar.SECOND))
+ String.valueOf(rd.nextInt(100)) + ".jpg";
} else if (fileName.endsWith(".gif")) {
filename = String.valueOf(time.get(Calendar.YEAR))
+ String.valueOf(time.get(Calendar.MONTH))
+ String.valueOf(time
.get(Calendar.DAY_OF_MONTH))
+ String
.valueOf(time.get(Calendar.HOUR_OF_DAY))
+ String.valueOf(time.get(Calendar.MINUTE))
+ String.valueOf(time.get(Calendar.SECOND))
+ String.valueOf(rd.nextInt(100)) + ".gif";
}
File f1 = new File(uploadPath + filename);
// 打印相对路径
// System.out.print(f1.getAbsolutePath());
// 数据库中存储图片路径为:
// http://127.0.0.1:8080/MailSend/upload/images/1.jpg
// 要写入数据库的路径 imageUrl
file.write(f1);
imageUrl = imagePath + "products/" + filename;
if(flag){
//成功后跳转到主面
response.sendRedirect("index.jsp");
}
else {
response.sendRedirect("error.jsp"); //失败后跳转到错误页
}
}
}
// 跳转到上传成功提示页面
} catch (Exception e) {
// 可以跳转出错页面
}
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}