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】

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM