JSP+Servlet实现文件上传

时间:2022-07-12 21:06:52

需要两个jar包支持:点我下载
demo如下:
index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="uploadServlet" method="post" enctype="multipart/form-data">
图书名称:<input type="text" name="bookName" />
文件:<input type="file" name="file" />
<input type="submit" value="提交" />
</form>
</body>
</html>

其中的servlet如下:
UploadServlet.java

package cn.bestchance.servlet;

import java.io.File;
import java.io.IOException;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/uploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String bookName = "";
try {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);

List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
if(!fileItem.isFormField()){

String fileName = fileItem.getName();
//限制只能上传图片
if(fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png")){
String rootPath = getServletContext().getRealPath("image/");
File file = new File(rootPath, fileName);
//写入文件
fileItem.write(file);
}else{//上传的不是图片
response.getWriter().println("<script>alert('请上传格式为jpg,png,jpeg类型的图片!!!');window.location.href='index.jsp'</script>");
}
}else{ //不是文件类型,则为普通属性
if("bookName".equals(fileItem.getFieldName())){
bookName = fileItem.getString("utf-8");
System.out.println(bookName);//输出到控制台测试
}
}
}
} catch (Exception e) {
response.getWriter().println("<script>alert('上传图片异常,请重新操作!!!');window.location.href='index.jsp'</script>");
}
}
}

需要注意的是:由于表单提交时设置了这个属性:enctype=”multipart/form-data”
因此在servlet中不能使用request.getParamter();方法来获取表单普通属性,因此普通属性的获取需在if中判断,例如demo中的bookName,且需要使用该条语句设置编码格式 bookName = fileItem.getString(“utf-8”);