文件上传,后台代码 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; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; @WebServlet(name="upload",urlPatterns={"/upload"}) //处理文件上传的Servlet需要使用@MultipartConfig注解来修饰 @MultipartConfig public class UploadServlet extends HttpServlet { public void service (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html; charset=GBK"); //设置响应的报头信息 PrintWriter out = response.getWriter(); //获取响应的对象输出流 request.setCharacterEncoding("GBK"); //对客户端请求进行重新编码 Part part = request.getPart("file"); //获取指定的文件上传域。若为getParts()则可以获取所有的文件上传域 out.println("上传文件的类型为:"+part.getContentType()+"<br/>"); //获取part上传文件的文件类型 Collection<String> headerNames = part.getHeaderNames(); //part.getHeaderNames()获取文件上传域的Header Name for(String headerName : headerNames){ out.println(headerName+"--->"+part.getHeader(headerName)+"<br/>"); } String fileNameInfo = part.getHeader("content-disposition"); String fileName=fileNameInfo.substring(fileNameInfo.indexOf("filename=\"")+13,fileNameInfo.length() - 1); System.out.print(getServletContext().getRealPath("/uploadFiles")+"/"+fileName); part.write(getServletContext().getRealPath("/uploadFiles")+"/"+fileName); } } 前端代码: <%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %> <!DOCTYPE html> <html> <head> <title>文件上传</title> </head> <body> <form method="post" action="upload" enctype="multipart/form-data"> 选择文件:<input type="file" id="file" name="file" /><br/> <input type="submit" value="上传" /><br/> </form> </body> </html>
|