圖片上傳功能實現

圖片上傳功能實現

java後端實現代碼:

 @ResponseBody
    @RequestMapping("/home/updateInfoForm")
    public Map<String, Object> update(MultipartFile imgFile, @RequestParam Map<String, Object> map, HttpServletRequest request) {
        if (imgFile != null) {
//            -----------------------------------------------------
            //獲取文件輸入流
            InputStream inputStream = null;
            try {
                inputStream = imgFile.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //獲取服務器存放圖片的真實路徑
            String realPath = this.getRealPath("/upload", request);

            //獲取文件名稱並且進行重命名
            String originalFilename = imgFile.getOriginalFilename();
            String newName = this.getNewName(originalFilename);

            //在服務器上創建新文件
            FileOutputStream fileOutputStream = null;
            File file = new File(realPath, newName);
            try {
                fileOutputStream = new FileOutputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            //文件複製
            try {
                IOUtils.copy(inputStream, fileOutputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //將路徑保存到map數據庫中
            map.put("avatar", "upload/" + newName);

//-----------------------------------------------------------------
        }
        HttpSession session = request.getSession();
        User user_model = (User) session.getAttribute("_USER_MODEL");
        int id = user_model.getId();
        map.put("id", id);

        int i = userService.updateInfo(map);
        System.out.println("i的值:" + i);
        if (i > 0) {
            User userAfterUpdate = userService.getUserById(id);
            session.setAttribute("_USER_MODEL", userAfterUpdate);

            map.put("success", true);

        } else {
            map.put("message", "更新失敗");
        }
        return map;
    }

    //傳入一個文件夾的名稱,獲取它在服務器上的真實路經
    private String getRealPath(String s, HttpServletRequest request) {
        String realPath = request.getSession().getServletContext().getRealPath(s);
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdir();
        }
        return realPath;
    }

    //防止文件重名,重命名
    private String getNewName(String oldName) {
        UUID uuid = UUID.randomUUID();
        String newName = uuid + oldName.substring(oldName.lastIndexOf("."));
        return newName;
    }
}

jsp部分:

<%@ page language="java" contentType="text/html; charset=UTF-8"
       pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
   String path = request.getContextPath();
   String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE>
<html>
<head>
   <base href="<%=basePath%>">
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>更新資料</title>
   <%@ include file="include/styles.jsp" %>
</head>
<body>

<jsp:include page="include/header.jsp"/>

<div class="container">
   <div class="row">
      <div class="col-xs-9">
            <div class="panel panel-default">
               <div class="panel-heading">
                  更新資料
               </div>
               <div class="panel-body">
                  <c:if test="${!empty _USER_MODEL.avatar}">
                     <p class="text-center">
                        <img src="${_USER_MODEL.avatar}" width="80px" height="80px" style="border-radius: 40px;">
                     </p>
                  </c:if>
                  <form class="form-horizontal" id="infoForm" method="post" enctype="multipart/form-data">

                     <div class="form-group">
                        <label for="imgFile" class="col-sm-2 control-label">頭像</label>
                        <div class="col-sm-10">
                           <input type="file" class="form-control" id="imgFile" placeholder="" name="imgFile">
                        </div>
                     </div>
                     <div class="form-group">
                        <label for="email" class="col-sm-2 control-label">郵箱地址</label>
                        <div class="col-sm-10">
                           <input type="email" id="email" class="form-control" value="${_USER_MODEL.email }"
                                 readonly="readonly">
                        </div>
                     </div>

                     <div class="form-group">
                        <label for="userName" class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-10">
                           <input type="text" class="form-control" name="userName" id="userName"
                                 placeholder="姓名,大名" value="${_USER_MODEL.userName}">
                        </div>
                     </div>
                     <div class="form-group">
                        <label for="nickName" class="col-sm-2 control-label">暱稱</label>
                        <div class="col-sm-10">
                           <input type="text" class="form-control" name="nickName" id="nickName"
                                 placeholder="暱稱,小名" value="${_USER_MODEL.nickName}">
                        </div>
                     </div>
                     <div class="form-group">
                        <label for="age" class="col-sm-2 control-label">年齡</label>
                        <div class="col-sm-10">
                           <input type="number" class="form-control" name="age" id="age" placeholder="年齡"
                                 value="${_USER_MODEL.age}">
                        </div>
                     </div>
                     <div class="form-group">
                        <label for="introduction" class="col-sm-2 control-label">個人介紹</label>
                        <div class="col-sm-10">
                           <textarea class="form-control" name="introduction"
                                   id="introduction">${_USER_MODEL.introduction}</textarea>
                        </div>
                     </div>
                     <div class="col-sm-10 col-sm-offset-2 text-right">
                        <button type="submit" class="btn btn-default">更新信息</button>
                     </div>
                  </form>
               </div>
            </div>
      </div>
      <div class="col-xs-3">
         <jsp:include page="include/right.jsp"></jsp:include>
      </div>
   </div>
</div>

<%@ include file="include/scripts.jsp" %>


<script>
    var fileFlag = false;
    $(function () {
        $("#imgFile").blur(function (){
            $("#imgFile").each(function(){
                console.log($(this).val())
                if($(this).val()!="") {
                    fileFlag = true;
                }else{
                    fileFlag = false;
            }
            });
        })


      $('#infoForm').validate({
        submitHandler: function (form) {
            if (fileFlag) {
                //ajax提交
                $(form).ajaxSubmit({
                    url: 'home/updateInfoForm.action',
                    method: 'post',
                    // dataType: 'json',
                    success: function (data) {
                        //響應結果
                        if (data.success) {
                            alert('修改信息成功');
                            location.reload();
                        } else {
                            alert('信息修改失敗:' + data.message);
                        }
                    }
                });
            }else{
                $.post('home/updateInfoForm.action', $(form).serialize(), function (data) {
                    if (data.success) {
                        alert('修改信息成功');
                        location.reload();
                    } else {
                        alert('信息修改失敗:' + data.message);
                    }
                });
         }
      },
         rules: {
            userName: {
               required: true
            },
            nickName: {
               required: true
            },
            age: {
               required: true
            }/*,
            imgFile: {
               required: true
            }*/
         }
      });

   });
</script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章