单文件上传
<!--记得要使用post方法,和指定格式-->
<form action="/LayUI/up" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="上传">
</form>
在servlet中通过name获取文件路径,MultipartConfig注释在使用Part类时要存在,不然会报错
@WebServlet(name = "UpServlet",urlPatterns = "/up")
@MultipartConfig(location = "F:/work/img",fileSizeThreshold = 1024*102,maxFileSize = 1024*1024*5,maxRequestSize = 1024*1024*5*5)
public class UpServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part part = request.getPart("file");
//获取文件名
System.out.println(part.getSubmittedFileName());
//随机生成文件名,可以防止上传文件重复
String filename = UUID.randomUUID().toString()+".jpg";
//文件复制,放在location目录下
part.write(filename);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
多文件上传
<form action="/LayUI/ups" method="post" enctype="multipart/form-data">
<input name="file" type="file"><br>
<input name="file" type="file"><br>
<input name="file" type="file"><br>
<input name="file" type="file"><br>
<input type="submit" value="上传">
</form>
这里只是简单的模拟,一般是通过foreach循环判断你选择了多少个文件
@WebServlet(name = "UPsServlet",urlPatterns = "/ups")
@MultipartConfig(location = "F:/work/img",fileSizeThreshold = 1024*102,maxFileSize = 1024*1024*5,maxRequestSize = 1024*1024*5*5)
public class UPsServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Collection<Part> parts = request.getParts();
List<String> up_list=new ArrayList<>();
String path="F:/work/img";
for (Part part : parts) {
String filename = UUID.randomUUID().toString()+".jpg";
if(!part.getSubmittedFileName().equals("")){//如果没有选择图片不保存与展示
part.write(path+ File.separator +filename);
//用于文件展示,upload是虚拟路径,因为你转发的是jsp页面,直接使用真实路径是无法显示图片的
up_list.add("/upload/"+filename);
}
}
request.setAttribute("up_list",up_list);
request.getRequestDispatcher("show.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
设置虚拟路径
1、找到tomcat目录下conf--》 server.xml文件中,找到Host标签,在里面写上
<Context path="/upload" docBase="f:/work/img"/>
<!--path是虚拟路径名称,docBase是真实路径名-->
2、如果是使用idea,需要在配置tomcat里面勾选上如下所示复选框,否则使用虚拟路径无法生效