package com.demo;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "FileUploadServlet", urlPatterns = {"/fileUpload.do"})
@MultipartConfig(location = "D:\\", fileSizeThreshold = 1024)
public class FileUploadServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // 设置请求和响应的字符编码为UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 返回Web应用程序文档根目录
        String path = this.getServletContext().getRealPath("/");
        String mnumber = request.getParameter("mnumber");
        Part p = request.getPart("fileName");

        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<font color = '#0000ff'>");
        
        if (p.getSize() > 1024 * 1024) {    // 上传的文件不能超过1MB大小
            p.delete();
            out.println("文件太大，不能上传！");
        } else {
            path = path + "\\student\\" + mnumber;
            File f = new File(path);
            if (!f.exists()) {  // 若目录不存在，则创建目录
                f.mkdirs();
            }
            
            // 得到文件名
            String h = p.getHeader("content-disposition");
            String fname = getFileName(h);
            
            p.write(path + "\\" + fname);
            out.println("文件上传成功！");
        }
        out.println("</body></html>");
    }

    private String getFileName(String contentDisposition) {
        String[] parts = contentDisposition.split(";");
        for (String part : parts) {
            if (part.trim().startsWith("filename")) {
                return part.substring(part.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
}