如何在SpringBoot當中上傳多個圖片或者上傳單個圖片 工具類


 

 

如何在SpringBoot當中上傳多個圖片【上傳多個圖片 】 附贈工具類


 

1.SpringBoot 上傳圖片工具類

 1 public class SpringUploadUtil {
 2 
 3     
 4     /***
 5      * 上傳圖片后返回文件名稱用於存儲數據庫
 6      * @author MRC
 7      * @date 2019年4月8日上午11:22:54
 8      * @return
 9      */
10     public static String uploadPics(List<MultipartFile> file){
11         
12         int index = 0;
13         StringBuffer sb = new StringBuffer();
14         
15         for (MultipartFile multipartFile : file) {
16             if (file.isEmpty()) {
17                 continue;
18             }
19             try {
20                 //工具類生成文件名
21                 String fileName = FileCreateNameUtils.toCreateName();
22                 //獲取文件后綴名
23                 String fileType  = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf("."));
24                 File f = new File("D:\\upload\\"+fileName+fileType);
25                 if (f.exists()) {
26                     //判斷這個文件是否存在,若存在則變換文件名 防止覆蓋
27                     fileName = FileCreateNameUtils.toCreateName();
28                 }
29                 byte[] bytes = multipartFile.getBytes();
30                 Path path = Paths.get("upload/" + fileName+fileType);
31                 //寫入磁盤
32                 Files.write(path, bytes);
33                 
34                 sb.append(StaticUtils.UPLOAD+fileName+fileType);
35                 index++;
36                 if (file.size() != index ) {
37                     sb.append(",");
38                 }
39             } catch (IOException e) {
40                 e.printStackTrace();
41             }
42         }
43         
44         return sb.toString();
45     }

 

 

經過工具類圖片上傳后,返回的字符串是用逗號分隔的圖片上傳后的路徑!

舉個栗子: upload/2019041615094470712493.jpg,upload/2019041615094470712456.jpg

 

**注明 文件名生成的工具類 按照時間戳和隨機字符串生成文件的名字

public class FileCreateNameUtils {
    
    
    
    public static final String numberChar = "0123456789";
    
    /***
     * 文件名生成工具類
     */

    public static String toCreateName() {

        return getNowDatetoString() + generateNum(10);

    }

    /***
     * 生成日期字符串 yyyyMMddHHmm
     * 
     * @author MRC
     * @date 2019年4月16日下午2:19:37
     * @return
     */
    public static String getNowDatetoString() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmm");
        String dateString = formatter.format(currentTime);
        return dateString;
    }
    
    /***
     * 生成隨機數
     * @author MRC
     * @date 2019年4月16日下午2:21:06
     * @param len
     * @return
     */
    public static String generateNum(int len) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < len; i++) {
            sb.append(numberChar.charAt(random.nextInt(numberChar.length())));
        }
        return sb.toString();
    }

 

2.在Controller層調用上傳圖片方法


 

 

    @PostMapping("orderComment")
    @ResponseBody
    public Map<String, Object> orderComment(HttpServletRequest request){
        
        Map<String, Object> map = new HashMap<>();
        
     // 從前台的請求當中取出 file文件類型 List
<MultipartFile> list = ((MultipartHttpServletRequest)request).getFiles("file"); String pics = null; if (list.size() != 0) { //上傳圖片 調用工具類上傳 返回上傳后文件的名字 pics = SpringUploadUtil.uploadPics(list); }
    
    // pics = "upload/2019041615094470712493.jpg,upload/2019041615094470712456.jpg"
}

 

上傳后返回 圖片路徑拼接的字符串  使用英文狀態下(,)分隔

 


3.前台上傳部分代碼示例

<html>
<body>
<h1>Spring Boot file upload example</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="Submit" />
</form>
</body>
</html>

 


4.參考博客:https://www.cnblogs.com/ityouknow/p/8298344.html

 


免責聲明!

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



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