servlet实现文件上传
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body >
<div style="text-align:center">
<form action="uploadServlet">
姓名:<input type="text" name="name"/><br>
<input type="file" name="uploadFile" id=""/><br>
<button type="submit">提交</button>
</form>
</div>
</body>
</html>
uploadServlet
package com.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.security.auth.x500.X500Principal;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.bean.ipLocation;
import com.db.Idb;
import com.db.Impl.dbImpl;
import com.entity.student;
@WebServlet("/uploadServlet")
public class addStudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIRECTORY = "upload";
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
String name ;
String relativePath;
public addStudentServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(request)) {
PrintWriter writer = response.getWriter();
writer.println("Error: 表单必须包含 enctype=multipart/form-data");
writer.flush();
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
upload.setHeaderEncoding("UTF-8");
String uploadPath =request.getServletContext().getRealPath(".") + File.separator + UPLOAD_DIRECTORY;
relativePath = File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
System.out.println(item.isFormField());
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
relativePath = relativePath+ File.separator + fileName;
System.out.println("."+relativePath.replace("\\", "/"));
System.out.println(filePath);
picPath = filePath;
item.write(storeFile);
request.setAttribute("message",
"文件上传成功!");
String name = item.getFieldName();
System.out.println(name);
}else {
String name = item.getFieldName();
System.out.println(name);
System.out.println("------------------------");
String cString = "sclass";
if(name.equals("name")) {
name=item.getString("utf-8");
System.out.println(sclass);
}
}
}
request.getRequestDispatcher("./index.jsp").forward(request, response);
}else {
boolean result = db.addStudent(student);
if (result) {
request.setAttribute("result", "1");
request.getRequestDispatcher("./index.jsp").forward(request, response);
}else {
request.setAttribute("result", "2");
}
}
}
} catch (Exception ex) {
request.setAttribute("message",
"错误信息: " + ex.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
- isFormField方法isFormField方法用于判断FileItem类对象封装的数据是否属于一个普通表单字段,还是属于一个文件表单字段,如果是普通表单字段则返回true,否则返回false。
- getFileName()方法 如果是文件获取文件名,如果为普通字段获取字段的name属性值
- getName() 获取文件上传字段中的文件名
- getString() 讲数据内容以字符串形式返回。
- write() write方法用于将FileItem对象中保存的主体内容保存到某个指定的文件中。如果FileItem对象中的主体内容是保存在某个临时文件中,该方法顺利完成后,临时文件有可能会被清除。该方法也可将普通表单字段内容写入到一个文件中,但它主要用途是将上传的文件内容保存在本地文件系统中。