1. 程式人生 > 實用技巧 >【轉】 springBoot(3)---目錄結構,檔案上傳

【轉】 springBoot(3)---目錄結構,檔案上傳

【轉】 springBoot(3)---目錄結構,檔案上傳

目錄結構,檔案上傳

一、目錄結構

1、目錄講解

src/main/java:存放程式碼
src/main/resources
static: 存放靜態檔案,比如 css、js、image, (訪問方式 http://localhost:8080/js/main.js)
templates:存放靜態頁面jsp,html,tpl
config:存放配置檔案,application.properties
resources:

2、同個檔案的載入順序,靜態資原始檔

Spring Boot 預設會挨個從
META/resources > resources > static > public 裡面找是否存在相應的資源,如果有則直接返回。

什麼意思呢,就是比如你有個index.html檔案,springboot預設放在以上資料夾是可以訪問到的,而且是按照這個順序訪問。

案例:我在,resources,static ,public ,templates都放一個index.html檔案,然後輸入:localhost:8080,看訪問的是哪個index.html

可以看出:首先訪問就是resources裡面的index.html

text檔案預設是訪問不了的,就算你的露筋是localhost:8080/text/index.html也是訪問不了的。

不過,你在application.properties配置如下,就可以訪問了

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/

二、檔案上傳

一、war包方式進行上傳

springboot檔案上傳的物件是MultipartFile,它是file的子類,源自

1)靜態頁面直接訪問:localhost:8080/index.html
注意點:
如果想要直接訪問html頁面,則需要把html放在springboot預設載入的資料夾下面
2)MultipartFile

物件的transferTo方法,用於檔案儲存(效率和操作比原先用FileOutStream方便和高效)

案例:在static檔案目錄下,

upload.html

<!DOCTYPE html>
<html>
  <head>
    <title>uploadimg.html</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  </head>

  <body>
     <!--涉及檔案上傳,這裡就需要multipart/form-data-->
      <form enctype="multipart/form-data" method="post" action="/upload">
        檔案:<input type="file" name="head_img"/>
        姓名:<input type="text" name="name"/>
        <input type="submit" value="上傳"/>
       </form>
   
  </body>
</html>

FileController類

package com.jincou.ocontroller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;


import com.jincou.model.JsonData;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileController {

       //檔案放在專案的images下
        private static final String filePath =  "C:\\Users\\chenww\\Desktop\\springbootstudy\\springbootstudy\\src\\main\\resources\\static\\images\\";
    
         @RequestMapping(value = "upload")
        @ResponseBody
        public JsonData upload(@RequestParam("head_img") MultipartFile file,HttpServletRequest request) {
          
             //file.isEmpty(); 判斷圖片是否為空
             //file.getSize(); 圖片大小進行判斷
             
             String name = request.getParameter("name");
             System.out.println("使用者名稱:"+name);
            
             // 獲取檔名
            String fileName = file.getOriginalFilename();            
            System.out.println("上傳的檔名為:" + fileName);
            
            // 獲取檔案的字尾名,比如圖片的jpeg,png
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            System.out.println("上傳的字尾名為:" + suffixName);
            
            // 檔案上傳後的路徑
            fileName = UUID.randomUUID() + suffixName;
            System.out.println("轉換後的名稱:"+fileName);
            
            File dest = new File(filePath + fileName);
           
            try {
                file.transferTo(dest);
                //上傳成功
                return new JsonData(0, fileName);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
              //上傳失敗
            return  new JsonData(-1, "fail to save ", null);
        }
}
JsonData物件,用來返回狀態
package com.jincou.model;

import java.io.Serializable;

public class JsonData implements Serializable {
    private static final long serialVersionUID = 1L;

    //狀態碼,0表示成功,-1表示失敗
    private int code;
    
    //結果
    private Object data;

    //錯誤描述
    private String msg;
    
    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public JsonData(int code, Object data) {
        super();
        this.code = code;
        this.data = data;
    }

    public JsonData(int code, String msg,Object data) {
        super();
        this.code = code;
        this.msg = msg;
        this.data = data;
    }            
}

效果:

這裡面如果你想限制上傳問價大小,可以在新增如下:

           //檔案大小配置,啟動類裡面配置
        
            @Bean  
            public MultipartConfigElement multipartConfigElement() {  
                MultipartConfigFactory factory = new MultipartConfigFactory();  
                //單個檔案最大  
                factory.setMaxFileSize("10240KB"); //KB,MB  
                /// 設定總上傳資料總大小  
                factory.setMaxRequestSize("1024000KB");  
                return factory.createMultipartConfig();  
            }  

總結:

1.其實在正式專案裡,這裡的檔案上傳地址不會是在本專案裡,而是會指定一個檔案伺服器:

常用檔案伺服器:fastdfs,阿里雲oss,nginx搭建一個簡單的檔案伺服器

2.有關單個檔案最大值,路徑最好是配置在配置檔案裡,這樣後期好維護。

想太多,做太少,中間的落差就是煩惱。想沒有煩惱,要麼別想,要麼多做。上尉【5】