import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@WebServlet(name = "UpLoadServlet" ,value="/upload")
@MultipartConfig //使用MultipartConfig注解标注改servlet能够接受文件上传的请求
public class UpLoadServlet extends HttpServlet {
@Override
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");
// 当添加了注解MultipartConfig是可以使用 getParameter()方法获得普通框 选项的值
// 不加的话不能获得二进制数据 在表单from 后面记得添加 Multifi** 告知浏览器有文件上传
String studentName = request.getParameter("studentName");
// ------------------ 文件上传部分----------------------------------------
// 获得 文件对象
Part part = request.getPart("studentPhoto");
// 获得文件名
String fileName = part.getSubmittedFileName();
// 截取后缀名
String ext = fileName.substring(fileName.indexOf("."));
// 获得新的文件名
String uuid = UUID.randomUUID().toString();
String newfileName = uuid+ext;
// 获得文件存放的地址
String path = this.getServletContext().getRealPath("/imgs");
// 判断文件夹 imgs 是否存在
File file =new File(path);
if (!(file.exists())){
file.mkdir();
}
// 得到保存的文件路径
String save_path = path +File.separator + newfileName;
// 直接用 part对象 写到指定路径中去
part.write(save_path);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}