/*
* @Description //TODO 文件上传
* @Date 2019/11/26 16:36
* @Param
* @return
**/
//1.在接收请求的Servlet上添加 @MultipartConfig 注解,标识该Servlet会接收文件内容;
@MultipartConfig
@WebServlet("/fileServlet1")
public class FileServlet1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");//解决post请求乱码
//2.通过 request.getPart("文件参数名") 得到一个Part对象,该对象封装了文件表单项相关的所有内容;
Part file = request.getPart("file");
//3.通过 part对象.getSubmittedFileName() 可以得到文件的名称;
String subName = file.getSubmittedFileName();
//4.通过 part对象.getInputStream() 可以得到流对象,读取文件的内容;
InputStream fis = file.getInputStream();
//创建保存的文件夹
File srcFile = new File("C:\\Users\\Desktop\\upload");
if (!srcFile.exists()) {
srcFile.mkdirs();
}
//5.通过 输出流,把文件的内容输出到服务器本地文件中。
FileOutputStream fos = new FileOutputStream(srcFile+"/"+subName);
byte[] by = new byte[1024];
int len;
while ((len = fis.read(by)) != -1) {
fos.write(by, 0, len);
}
fos.close();
}
html代码
<body>
<!--文件上传三要素 必须是post请求 enctype="multipart/form-data" type 必须是 file 属性-->
<form method="post" enctype="multipart/form-data" action="/fileServlet1">
姓名<input type="text" name="username"> <br>
文件<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
</body>