html表单提交图片,servlet接收的方法

用<input type="file" name="file"> 上传的是图片,要将图片保存到本地(比如D盘下)

servlet应该怎么写啊

package com.controller;

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.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

@MultipartConfig // 表示控制器支持文件上传
@WebServlet("/Test")
public class Test extends HttpServlet {

    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Part part = request.getPart("file");
        if (part != null) {
            String img = "image/jpg,image/jpeg,image/png,image/gif";
            List<String> imgList = Arrays.asList(img.split(","));
            String contentType = part.getContentType();
            if (imgList.contains(contentType) == false) {
                response.sendRedirect("${pageContext.request.contextPath}/路径?fileError=文件类型错误");
            } else {
                // 获取文件真实名:Servlet 3.0不提供获取上传文件名的方法,通过请求头信息间接获取
                String header = part.getHeader("content-disposition");
                String realName = header.substring(header.indexOf("filename=") + 10, header.length() - 1);
                // 获取真实文件名的后缀
                String fileSuffix = realName.substring(realName.lastIndexOf("."));// 切割文件名

                // 使用时间戳+随机数自动生成文件名,避免文件名重复问题
                // JDK1.8 日期时间类
                LocalDateTime now = LocalDateTime.now();// 当前系统时间
                DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");// 日期格式
                // 将当前日期时间转成字符串
                String formatDate = ofPattern.format(now);
                // 随机数
                int random = (int) (Math.random() * 1000 + 1);
                // 拼接
                StringBuffer stringBufferFileName = new StringBuffer();
                stringBufferFileName.append(formatDate).append(random);

                // 将文件存储在指定服务器中(本地电脑D盘)
                File file = new File("D:\\");
                if (!file.exists()) {
                    file.mkdirs();
                }
                // 将文件写入指定位置
                String filePath = file.getPath() + File.separator + stringBufferFileName + fileSuffix;
                part.write(filePath);
            }
        }
    }
}

有帮助 望采纳