溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring Boot 會(huì)員管理系統(tǒng)之處理文件上傳功能

發(fā)布時(shí)間:2020-10-04 03:56:16 來源:腳本之家 閱讀:166 作者:longer499@163.com 欄目:編程語言

溫馨提示

Spring Boot會(huì)員管理系統(tǒng)的中,需要涉及到Spring框架,SpringMVC框架,Hibernate框架,thymeleaf模板引擎。所以,可以學(xué)習(xí)下這些知識(shí)。當(dāng)然,直接入門的話使用是沒問題,但是,涉及到一些異常和原理的話可能就有些困難。

1. 前端部分

在前端部分addMember.html是通過form表單來提交會(huì)員的信息,其中就包括了圖片上傳功能(這里涉及了文件上傳操作),表單部分代碼如下:

<form th:action="@{/admin/addMember}" method="post" enctype="multipart/form-data" id="addMember">
              <div class="file-field input-field">
                <div class="btn">
                  <span>選擇頭像文件</span>
                  <input id="file" type="file" name="iconPath" multiple="" placeholder="選擇文件" accept="image/*" onchange="changeToop()">
                </div>
                <div class="file-path-wrapper">
                  <!--<input class="file-path validate" type="text" placeholder="Upload one or more files">-->
                  <img id="myimg" src="assets/iconPath/common.jpg" class="img-responsive img-thumbnail"  />
                </div>
                <!--頭像文件上傳預(yù)覽-->
                <script>
                  function Id(id){
                    return document.getElementById(id);
                  }
                  function changeToop(){
                    var file = Id("file");
                    if(file.value===''){
                      //設(shè)置默認(rèn)圖片
                      Id("myimg").src='assets/iconPath/common.jpg';
                    }else{
                      preImg("file","myimg");
                    }
                  }
                  //獲取input[file]圖片的url Important
                  function getFileUrl(fileId) {
                    var url;
                    var file = Id(fileId);
                    var agent = navigator.userAgent;
                    if (agent.indexOf("MSIE")>=1) {
                      url = file.value;
                    } else if(agent.indexOf("Firefox")>0) {
                      url = window.URL.createObjectURL(file.files.item(0));
                    } else if(agent.indexOf("Chrome")>0) {
                      url = window.URL.createObjectURL(file.files.item(0));
                    }
                    return url;
                  }
                  //讀取圖片后預(yù)覽
                  function preImg(fileId,imgId) {
                    var imgPre =Id(imgId);
                    imgPre.src = getFileUrl(fileId);
                  }
                </script>
              </div>
              
              .......
              
            </form>

這里有一個(gè)注意事項(xiàng):因?yàn)樯婕拔募蟼鳎栽趂orm中需要加入enctype="multipart/form-data",而且就是input中的name屬性是與后端中的Controller映射方法的傳入?yún)?shù)名是一一對(duì)應(yīng)的。

2. 后端代碼實(shí)現(xiàn)

后端中對(duì)于SpringMVC框架可以對(duì)于文件進(jìn)行處理然后我們可以通過傳入?yún)?shù)的方式來接收文件

2.1 Controller處理傳入文件

代碼如下:

@PostMapping("/addMember")
  public String addMember(Member member, String gradeName, MultipartFile icon, Map<String, Object> model) {
    //處理上傳文件
    try {
      if (icon == null)//首先判斷上傳文件不為null
        return "error";
      if (icon.getOriginalFilename().equals("")) //如果上傳文件的原名為空字符串,則證明使用了默認(rèn)圖像
        member.setIconPath("/assets/icon/common.jpg"); //設(shè)置為我們的默認(rèn)圖像路徑
      else
        //這里通過了自己編寫的文件上傳工具類來處理上傳的MultipartFile,文件名設(shè)置為通過UUID產(chǎn)生的字符串
        member.setIconPath(FileUploadUtil.upload(icon, "/assets/icon/", UUIDRandomUtil.get32UUID()));
    } catch (Exception e) {
      e.printStackTrace();
      return "error";
    }
    
    .......
    
    return "addMemberSuccess";
  }

2.2 FileUploadUtil工具類保存文件

在Controller的MultipartFile文件傳入后需要進(jìn)一步,轉(zhuǎn)變?yōu)镕Ile并且保存到磁盤當(dāng)中,所以我分開處理,把Controller的傳入文件交給FileUploadUtil工具類來處理,具體的代碼如下:

public class FileUploadUtil {
  /**
   * 上傳文件
   * @param multipartFile multipartFile
   * @param prefixPath 前綴路徑,相對(duì)于整個(gè)項(xiàng)目中的路徑,路徑最前面不用加入“/”
   * @param fileName 上傳后的文件名
   * @return 上傳后最終的相對(duì)路徑+文件名
   * @throws Exception 有可能空指針異常和IO異常
   */
  public static String upload(MultipartFile multipartFile, String prefixPath, String fileName) throws Exception {
    //得出上傳的絕對(duì)路徑
    String uploadPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() +"/static"+ prefixPath;
    File file = new File(uploadPath);
    if (!file.exists())
      if (file.mkdirs())
        System.out.println("成功創(chuàng)建目錄");
    //獲取上傳的后綴名
    String suffixName = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
    //新建最終確定的文件
    file = new File(uploadPath+fileName+suffixName);
    multipartFile.transferTo(file);
    return prefixPath+fileName+suffixName;
  }
}

上面中的ClassUtils是Spring提供的一個(gè)工具類,而調(diào)用方法getDefaultClassLoader().getResource("").getPath()是獲取當(dāng)前項(xiàng)目classpath下的路徑。

以上便是本系統(tǒng)中關(guān)于文件上傳的部分內(nèi)容,該系統(tǒng)的源碼以上傳GitHub和下載源碼

總結(jié)

以上所述是小編給大家介紹的Spring Boot 會(huì)員管理系統(tǒng)之處理文件上傳功能,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI