Servlet 上传文件

image.png

UploadServlet

package com.baozi;
import java.io.IOException;
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 javax.servlet.http.Part;
import java.io.PrintWriter;
import javax.servlet.annotation.MultipartConfig;
@WebServlet("/UploadServlet")
@MultipartConfig()
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Part part = request.getPart("file1");               
        String submittedFileName = part.getSubmittedFileName();
        System.out.println("submittedFileName: "+submittedFileName);
        System.out.println("ContentType: "+part.getContentType());
        System.out.println("Size: "+part.getSize());    
        String header=part.getHeader("content-disposition");
        int index=header.lastIndexOf("\\");
        System.out.println("content-disposition: "+header);
        System.out.println(header);
        String s=header.substring(index,header.length()-1);
        System.out.println(s);
        part.write("D:/workspace/upload"+s);                    
        out.write("文件上传成功");                                
    }
}

upload.jsp

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




文件上传


选择文件

Console output:

submittedFileName: G:Downloadslivev4.mp4
ContentType: video/mp4
Size: 5365661
content-disposition: form-data; name="file1"; filename="G:\Downloads\livev\4.mp4"
form-data; name="file1"; filename="G:\Downloads\livev\4.mp4"
\4.mp4

你可能感兴趣的:(Servlet 上传文件)