关于springmvc上传图片

最近在项目中需要实现图片的上传,并且成功后返回图片上传保存路径,通过查找资料探索研究,实现了项目功能需求,记在这方便自己以后查阅,也为有同样需求的码友分享,功能实现比较简单,如果有好的建议和实现方法,还望多多指教。 

主要将实现一下两个功能: 
1、使用commons-fileupload实现文件的上传(包括图片); 

2、使用jquery-form.js实现表单提交成功的回调函数。 

3,spring的管理还需要:commons-io-2.2.jar

代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>H5后台管理系统</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="JS/jquery-1.8.3.js"></script>
    <link rel="stylesheet" href="CSS/addGame.css" />
    <script type="text/javascript">
         function login(){
             var gid=$("#gid").val();
             var gimg=$("#gimg").val();
            /*var lujing=$("#gimg").attr("src"); */
            var gname=$("#gname").val();
            var giIntroduction=$("#giIntroduction").val();
            var gtype=$("#gtype").val();
            var gtime=$("#gtime").val();
            var gurl=$("#gurl").val();
            var gjishu=$("#gjishu").val();
            var gopen=$("#gopen").val();
            var goptime=$("#goptime").val();
            var gtypeurl=$("#gtypeurl").val();
            if(gid==""||gimg==""||gname==""||giIntroduction==""||gtype==""||gtime==""||gurl==""||gopen==""||goptime==""||gtypeurl==""){
                 alert("请认真填写每一项。");
                 return ;
            }else{
                $("#formtj").submit();
            }          
         }
         function reset001(){
            $("#formtj input").val("");
         }
 </script>
</head>
<body>
    <form action="/BigMillionaire/MyBox/addGameSys.do" enctype="multipart/form-data" method="post" id="formtj" name="formtj">
        <div class="all">
            <div class="top">欢迎来到H5后台管理系统</div>
            <!--中部样式-->
            <div class="center">
                <div class="center001">
                    <label class="usernamebutton">游戏ID</label>
                    <input class="username_inpu lable01" id="gid" type="text" name="game_id" value="" />
                </div>

                <div class="center001 mtop ">
                    <label>游戏icon</label>
                    <input class="incon" id="game" name="gameimg" type="file"  />
                </div>

                <div class="center001 mtop ">
                    <label class="usernamebutton">游戏名</label>
                    <input class="username_inpu lable02" id="gname" type="text" name="game_name"value="" />
                </div>

                <div class="center001 mtop "> 
                    <label class="usernamebutton">游戏介绍</label>
                    <input class="username_inpu lable03" id="giIntroduction" type="text" name="game_shuoMing" value="" />
                </div>

                <div class="center001 mtop ">
                    <label  class="usernamebutton">游戏类型</label>
                    <select name="game_type" class="Dropbox lable05" id="gtype" value="">
                        <option value="1">飞行射击</option>
                        <option value="2">挂机放置</option>
                        <option value="3">角色扮演</option>
                        <option value="4">益智休闲</option>
                    </select>
                </div>

                <div class="center001 mtop ">
                    <label class="usernamebutton">上线时间</label>
                    <input class="username_inpu lable04" id="gtime" type="text" name="game_time" value=""  pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}"
                    required="required" autofocus />(格式:xxxx-xx-xx,最新栏,时间越大越靠前)
                </div>

                <div class="center001 mtop ">
                    <label class="usernamebutton">路径</label>
                    <input class="username_inpu lable06" id="gurl" type="text" name="game_url" value="" />
                </div>

                <div class="center001 mtop ">
                <label  class="usernamebutton">游戏级别</label>
                    <select name="game_jishu" id="gjishu" value="" class="Dropbox lable05">
                        <option>1</option>
                        <option>2</option>
                        <option>3</option>
                        <option>4</option>
                        <option>5</option>
                        <option>6</option>
                        <option>7</option>
                        <option>8</option>
                        <option>9</option>
                    </select>(推荐栏,数字越大越靠前)
                </div>

                <div class="center001 mtop ">
                    <label class="usernamebutton ">点击次数</label>
                    <input class="username_inpu lable04" id="gopen" value="" type="text" name="game_open"  />(最热栏,次数越大越靠前)
                </div>
                <div class="center001 mtop ">
                       <label class="usernamebutton">&nbsp;&nbsp;</label>
                    <select name="game_typeurl" id="gtypeurl" value="" class="Dropbox lable05">
                        <option value="xin.png"></option>
                        <option value="re.png"></option>
                        <option value="pu.png">普通</option>
                    </select>
                </div>

                <div class="center001 mtop ">
                    <button class="usernamebutton button001" type="button" onclick="login()" > 提交</button>
                    <button class="usernamebutton" type="button" id="reset" onclick="reset001()" >重置</button>
                </div>

            </div>
        </div>
    </form>
</body>
</html>

service代码;

@RequestMapping("/addGameSys")
    public ModelAndView addGameSys(HttpServletRequest req, HttpServletResponse resp,
            GameBean hear,
            // gameimg为表单名。将gameimg文件表单的数据封装成CommonsMultipartFile对象    [特别注意gameimg表单名,不能和GameBean类中的名字一样。]
            @RequestParam("gameimg") CommonsMultipartFile simimg)
            throws Exception {
        try {
            // 得到上传文件名称
            String simName = simimg.getOriginalFilename();
            // 以当前时间毫秒数重命名文件
            simName = System.currentTimeMillis()
                    + simName.substring(simName.lastIndexOf("."));
            // 得到指定文件的真实路径
            String path = req.getSession().getServletContext()
                    .getRealPath("/H52/img/icon/" + simName);
            // 将CommonsMultipartFile中的文件数据写入到指定文件中
            simimg.getFileItem().write(new File(path));
            // 将文件名存放入实体bean
            hear.setGame_img(simName);
            // hear.setIsimurl(simName);
            // 调用业务组件保存数据
            // service.add(bean);
            // adminService.addHear(hear);
            myBoxService.addGameBean(hear);
            //System.out.println(hear.toString());
            hear = null;
            return new ModelAndView("H52/jumpaddGame","type",1);
        } catch(Exception e) {
            return new ModelAndView("H52/jumpaddGame","type",0);
        }
        // return new ModelAndView("H52/jumpaddGame","type",1);
    }

实体bean,springmvc自动把数据封装到实体bean中

public class GameBean {
    private Integer game_id;// 游戏ID
    private String game_img; // icon
    private String game_name; //
    private String game_shuoMing; // 介绍
    private String game_type; // 类型(下拉框选择
    private String game_time; // 上线时间
    private String game_url; // 路径
    private String game_jishu; // 级别(1-9)数字越大越靠前(下拉框选择)
    private Integer game_open; // 点击次数
    private String game_opentime; // 第一次点击时间
    private String game_xingurl;
    private String game_reurl;
    private String game_typeurl; // 图片为新或热或普通 (下拉框选择)

xml配置文件:

  <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8" />
        <property name="maxUploadSize" value="32505856" /><!-- 上传文件大小限制为31M,31*1024*1024 -->
        <property name="maxInMemorySize" value="4096" />
    </bean>

完整:

Html代码  
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  3. <html>  
  4. <head>  
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  6. <title>文件上传</title>  
  7. <script src="static/js/jquery.min.js" type="text/javascript"></script>  
  8. <script type="text/javascript" src="static/js/jquery-form.js"></script>  
  9. <script type="text/javascript">  
  10.     function subimtBtn() {  
  11.         var form = $("form[name=fileForm]");  
  12.         var options  = {    
  13.             url:'${pageContext.servletContext.contextPath}/servlet/imageUploadServlet',    
  14.             type:'post',    
  15.             success:function(data)    
  16.             {    
  17.                 var jsondata = eval("("+data+")");  
  18.                 if(jsondata.error == "0"){  
  19.                     var url = jsondata.url;  
  20.                     alert(url)  
  21.                     $("#img").attr("src",url);  
  22.                 }else{  
  23.                     var message = jsondata.message;  
  24.                     alert(message);  
  25.                 }  
  26.             }    
  27.         };    
  28.         form.ajaxSubmit(options);  
  29.         //$("#fileForm").submit();  
  30.     }  
  31. </script>  
  32. </head>  
  33. <body>  
  34.             <div class="modal-body">  
  35.                   
  36.                 <form action='${pageContext.servletContext.contextPath}/servlet/imageUploadServlet' enctype="multipart/form-data" method="post" id="fileForm" name="fileForm">  
  37.                     <input type="file" name="filename">  
  38.                 </form>  
  39.                   
  40.             </div>  
  41.   
  42.             <div class="modal-footer">  
  43.                 <button class="btn btn-primary"  onclick="subimtBtn();">提交</button>  
  44.             </div>  
  45.   
  46.     <div>  
  47.      <img alt="img" src="" id="img">  
  48.     </div>  
  49. </body>  
  50. </html>  




servlet实现:imageUploadServlet.java 

Java代码  收藏代码
  1. package com.system.comtrol;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.PrintWriter;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.Arrays;  
  8. import java.util.Date;  
  9. import java.util.HashMap;  
  10. import java.util.Iterator;  
  11. import java.util.List;  
  12. import java.util.Random;  
  13. import javax.servlet.ServletException;  
  14. import javax.servlet.annotation.WebServlet;  
  15. import javax.servlet.http.HttpServlet;  
  16. import javax.servlet.http.HttpServletRequest;  
  17. import javax.servlet.http.HttpServletResponse;  
  18. import net.sf.json.JSONObject;  
  19. import org.apache.commons.fileupload.FileItem;  
  20. import org.apache.commons.fileupload.FileItemFactory;  
  21. import org.apache.commons.fileupload.FileUploadException;  
  22. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  23. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  24.   
  25.   
  26. /** 
  27.  * Servlet implementation class ImageUploadServlet 
  28.  */  
  29. @WebServlet("/servlet/imageUploadServlet")  
  30. public class ImageUploadServlet extends HttpServlet {  
  31.     private static final long serialVersionUID = 1L;  
  32.   
  33.     /** 
  34.      * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse 
  35.      *      response) 
  36.      */  
  37.     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  38.         try {  
  39.             PrintWriter out = response.getWriter();  
  40.             // 文件保存目录路径  
  41.             String savePath = request.getServletContext().getRealPath("/")+ "attached";  
  42.             // 文件保存目录URL  
  43.             String saveUrl = request.getContextPath() + "/attached";  
  44.             // 定义允许上传的文件扩展名  
  45.             HashMap<String, String> extMap = new HashMap<String, String>();  
  46.             extMap.put("image", "gif,jpg,jpeg,png,bmp");  
  47.             // 最大文件大小  
  48.             long maxSize = 1000000;  
  49.             response.setContentType("text/html; charset=UTF-8");  
  50.   
  51.             if (!ServletFileUpload.isMultipartContent(request)) {  
  52.                 out.println(getError("请选择文件。"));  
  53.                 return;  
  54.             }  
  55.             // 检查目录  
  56.             File uploadDir = new File(savePath);  
  57.             if (!uploadDir.isDirectory()) {  
  58.                 out.println(getError("上传目录不存在。"));  
  59.                 return;  
  60.             }  
  61.             // 检查目录写权限  
  62.             if (!uploadDir.canWrite()) {  
  63.                 out.println(getError("上传目录没有写权限。"));  
  64.                 return;  
  65.             }  
  66.   
  67.             String dirName = request.getParameter("dir");  
  68.             if (dirName == null) {  
  69.                 dirName = "image";  
  70.             }  
  71.             if (!extMap.containsKey(dirName)) {  
  72.                 out.println(getError("目录名不正确。"));  
  73.                 return;  
  74.             }  
  75.             // 创建文件夹  
  76.             savePath += dirName + "/";  
  77.             saveUrl += dirName + "/";  
  78.             File saveDirFile = new File(savePath);  
  79.             if (!saveDirFile.exists()) {  
  80.                 saveDirFile.mkdirs();  
  81.             }  
  82.             SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");  
  83.             String ymd = sdf.format(new Date());  
  84.             savePath += ymd + "/";  
  85.             saveUrl += ymd + "/";  
  86.             File dirFile = new File(savePath);  
  87.             if (!dirFile.exists()) {  
  88.                 dirFile.mkdirs();  
  89.             }  
  90.   
  91.             FileItemFactory factory = new DiskFileItemFactory();  
  92.             ServletFileUpload upload = new ServletFileUpload(factory);  
  93.             upload.setHeaderEncoding("UTF-8");  
  94.             List items = upload.parseRequest(request);  
  95.             Iterator itr = items.iterator();  
  96.             while (itr.hasNext()) {  
  97.                 FileItem item = (FileItem) itr.next();  
  98.                 String fileName = item.getName();  
  99.                 if (!item.isFormField()) {  
  100.                     // 检查文件大小  
  101.                     if (item.getSize() > maxSize) {  
  102.                         out.println(getError("上传文件大小超过限制。"));  
  103.                         return;  
  104.                     }  
  105.                     // 检查扩展名  
  106.                     String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();  
  107.                     if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {  
  108.                         out.println(getError("上传文件扩展名是不允许的扩展名。 只允许"    + extMap.get(dirName) + "格式。"));  
  109.                         return;  
  110.                     }  
  111.   
  112.                     SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");  
  113.                     String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;  
  114.                     try {  
  115.                         File uploadedFile = new File(savePath, newFileName);  
  116.                         item.write(uploadedFile);  
  117.                     } catch (Exception e) {  
  118.                         out.println(getError("上传文件失败。"));  
  119.                         return;  
  120.                     }  
  121.   
  122.                     JSONObject obj = new JSONObject();  
  123.                     obj.put("error", 0);  
  124.                     obj.put("url", saveUrl + newFileName);  
  125.                     out.println(obj.toString());  
  126.                 }  
  127.             }  
  128.         } catch (FileUploadException e1) {  
  129.             e1.printStackTrace();  
  130.         }  
  131.   
  132.     }  
  133.   
  134.     private String getError(String message) {  
  135.         JSONObject obj = new JSONObject();  
  136.         obj.put("error", 1);  
  137.         obj.put("message", message);  
  138.         return obj.toString();  
  139.     }  
  140.   
  141. }  




项目中依赖的主要jar:commons-fileupload-1.2.jar,commons-io-1.4.jar 
主要的两个js文件:jquery.min.js,jquery-form.js 
这些可以去网上下载

原文地址:https://www.cnblogs.com/sanhuan/p/4692169.html