Servlet3.0实现对文件的上传

1、代码

package com.servlets;

import java.io.IOException;
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;

@WebServlet("/uploadServlet")
@MultipartConfig //表明当前Servlet可以处理Multipart请求
public class UpLoadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	//获取服务端保存上传文件的目录路径
	String path = this.getServletContext().getRealPath("/images");
	//从Multipart请求中获取上传文件表单项
	Part part = request.getPart("photo");
	
	String fileName = part.getHeader("Content-Disposition");
	int index = fileName.lastIndexOf("=");
	String name = fileName.substring(index+2, fileName.length() - 1);
	
	//完成文件上传
	part.write(path + "/" + name);
	
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doGet(request, response);
}

}

<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding=“UTF-8”%>

Insert title here 文件:

</form>

2、截图

在这里插入图片描述

发布了47 篇原创文章 · 获赞 1 · 访问量 384

猜你喜欢

转载自blog.csdn.net/weixin_43925059/article/details/104750646