【JavaEE企业应用实战学习记录】servlet3.0上传文件

时间:2023-01-11 19:11:59
 <%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2016/10/6
Time: 14:20
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>upload</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
文件名:<input type="text" id="name" name="name"><br/>
选择文件:<input type="file" id="file" name="file"><br/>
<input type="submit" value="上传">
</form>
</body>
</html>
 package sanglp.servlet;

 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; /**
* Created by Administrator on 2016/10/6.
*/
@WebServlet(name = "upload",urlPatterns = {"/upload"})
@MultipartConfig
public class UploadServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//super.service(req, resp);
resp.setContentType("text/html;charset=GBK");
PrintWriter out=resp.getWriter();
//获取普通请求参数
String fileName=req.getParameter("name");
//获取上传文件的上传域
Part part=req.getPart("file");
out.println("上传文件的类型为"+part.getContentType()+"<br/>");
out.println("上传文件的大小为"+part.getSize()+"<br/>");
//获取文件上传的Header Name
Collection<String> headerNames=part.getHeaderNames();
for(String headerName:headerNames){
out.println(headerName+"-->"+part.getHeader(headerName)+"<br/>");
}
//将上传的文件写入服务器
part.write(getServletContext().getRealPath("/uploadFiles")+"/"+fileName);
}
}

【JavaEE企业应用实战学习记录】servlet3.0上传文件