java servlet 原生文件上传与下载(不依赖第三方jar包)

Servlet程序代码如下:
package com.example;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;


/**
 * 最关键的一步就是加此注解, 否则req.getParameter("username")就获取不到任何数据
 */
@MultipartConfig //如果是文件上传,必须加此注解
public class Upload extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        //设置请求编码格式
        req.setCharacterEncoding("UTF-8");

        String name = req.getParameter("username");
        System.out.println("username:" + name);

        //获取part对象
        Part part = req.getPart("photo");
        System.out.println(part);

        //通过Part对象得到上传的文件名
        String filename = part.getSubmittedFileName();
        System.out.println("上传的文件名:" + filename);

        //得到文件存放的路径
        String filepath = req.getServletContext().getRealPath("/");
        System.out.println("文件存放的路径:" + filepath);

        //上传文件到指定目录
        part.write(filepath + "/" + filename);
        System.out.println(filepath + "/" + filename);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
web.xml配置文件如下:



    
        Upload
        com.example.Upload
    
    
        Upload
        /upload
    

前端jsp页面如下:
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2023/2/15
  Time: 17:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title
<%--    --%>



用户名:
头像:

你可能感兴趣的:(java,java,tomcat)