JavaWeb实现图片上传功能

首先导入文件上传的jar包

 然后在Spring-servlet.xml文件中设置上传文件解析器

1     <!--上传文件解析器-->
2     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
3         <!-- 设定默认编码 -->
4         <property name="defaultEncoding" value="UTF-8"></property>
5         <!-- 设定文件上传的最大值5MB,5*1024*1024 -->
6         <property name="maxUploadSize" value="5242880"></property>
7     </bean>
8 
9     <mvc:resources location="/static/upload/" mapping="/upload/**"/>

前端页面一定要用post请求

在控制类中写实现功能,如果是一图片的命名可以用:用户名_png,不用再新建一个字段来存储。

 1     //插入(增加)--Post方法
 2     @RequestMapping(value = "/insert", method = RequestMethod.POST)
 3     public String insert(HttpServletResponse resp,HttpServletRequest req, Lwl lwl, MultipartFile fname) throws IOException {
 4         resp.setContentType("text/html;charset=UTF-8");
 5         log.debug("上传的文件:"+fname.getOriginalFilename());
 6         String sPath = req.getServletContext().getRealPath("/")+"/static/upload/";
 7         log.debug(sPath);
 8 
 9         fname.transferTo(new File(sPath+lwl.getLwla()+"_.png") );//保存文件
10 
11         lwl.setLwld(lwl.getLwla()+"_.png");//定义名字
12         if (lwlService.insertLwl(lwl)) {
13             return "redirect:/lwl";
14         } else {
15             req.setAttribute("error", "addLwl falilure");
16             return "addLwl";
17         }
18     }

在web下新建一个文件夹

 注意的是还要查看下面这个路径下有没有这个新建的文件夹,如果这里没有,就在这里新建一个即可。

 在前端显示页面加载即可

 然后就可以加载出来了

原创文章,转载请说明出处,谢谢合作
原文地址:https://www.cnblogs.com/lwl80/p/13653542.html