servlet实现上传功能

2023-12-25 16:42:50 浏览数 (1)

前端代码

注意: enctype属性

代码语言:javascript复制
<form action="tempServlet" method="post"  enctype="multipart/form-data">
		  file:<input  type="file"   name="fileName"/>
		 <input type="submit" name="submit"  value="submit"/>
	</form>

后端代码

代码语言:javascript复制
package com.imooc.servlet;

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("/tempServlet")
@MultipartConfig // servlet用于文件上传的注解
public class TempServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// part代表上传的文件
		Part part = request.getPart("fileName");

		//获取文件名称,需要在请求头中获得字符串,在截取字符串获取
		String header = part.getHeader("Content-Disposition");
		String fileName = header.substring(header.indexOf("filename="")   10, header.lastIndexOf("""));
		// 注意:part.getName() 
		//返回 <input type="file" name="fileName"/> 中的fileName,而不是上传的文件的名称
		String path = super.getServletContext().getRealPath("/fileupload");
		System.out.println("path---->" path);
				
		
		part.write(path "/" fileName);

	}

}

0 人点赞