| 方法 | 描述 |
| Part getPart(String name) | 获取请求中给定name的文件 |
| Collection | 获取所有的文件 |
| 方法 | 描述 |
| String getSubmittedFileName() | 获取文件名 |
| String getContentType() | 获取文件类型 |
| long getSize() | 获取文件的大小 |
| void write(String path) | 把文件数据写入指定路径的磁盘文件 |
实现程序,通过网页上传一张图片到服务器。
首先在webapp目录下创建一个upload.html文件,然后编写代码:
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>上传文件title>
- head>
- <body>
- <form action="upload" method="post" enctype="multipart/form-data">
- <input type="file" name="myfile">
- <input type="submit" value="上传">
- form>
- body>
- html>
注意:
(1) 上传文件时的请求为POST请求;
(2) form表单中要加上enctype属性,值为 "multipart/form-data"
- @WebServlet("/upload")
- @MultipartConfig
- public class UploadServlet extends HttpServlet {
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- Part part = req.getPart("myfile");
- System.out.println(part.getSubmittedFileName());//获取文件的真实名
- System.out.println(part.getSize());//获取文件大小
- System.out.println(part.getContentType());//获取文件类型
- part.write("D:/鸡哥/result.jpg");//把文件数据保存到硬盘
- }
- }
注意:

服务器:

硬盘:

请求:

