SpringBoot文件上傳


SpringBoot文件上傳:

  • 文件上傳和下載都是一件難題,今天我們的目的就是攻克這個難題

開始正題:

  • 首先創建一個SpringBoot項目,導入thmeleaf模板引擎和Web

  • Service層代碼:

package com.zhang.upload_demo01.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class UploadService {
   /*
   * MultipartFile 這個對象是SpringMVC/文件上傳的一個接受的類
   * 它的底層會自動去和httpServletRequest request中的request.getInputStream()融合
   * 從而達到文件上傳的效果
   *
   * 文件上傳的底層原理就是:request.getInputStream()
   * @param MultipartFile
   * */
   @Value("${file.uploadPath}")
   private String uploadPath;
   public String uploadImag(MultipartFile multipartFile,String dir){
       // 1:指定文件上傳目錄

       try {
           // 2:保證文件名的唯一,截取文件名后綴
           String originalFilename = multipartFile.getOriginalFilename(); //獲取文件 例如:aaa.jpg
           //截取文件名后綴
           String substring = originalFilename.substring(originalFilename.lastIndexOf(".")); // .jpg
           //生成唯一文件名
           String newFile = UUID.randomUUID().toString()+substring; // 拼接成為 dadesbawe-d5aa64.jpg
           //指定上傳目錄--->時間目錄
           SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
           String format = sdf.format(new Date()); //2022-02-16 日期目錄

           //String serverPath = "E://temp/";
           String serverPath = uploadPath;
           File targetFile = new File(serverPath+dir,format); // E://temp/${dir}/2022/02/16
           if (!targetFile.exists()){
               targetFile.mkdirs();
          }
           // 3:將文件上傳到指定目錄
           File targetFileName = new File(targetFile,newFile);
           //最終目錄: E://temp/${dir}//2022/02/16/dadesbawe-d5aa64.jpg

           multipartFile.transferTo(targetFileName);
           //將用戶選擇的aaa.jpg 上傳到E://temp/${dir}//2022/02/16/dadesbawe-d5aa64.jpg
           return dir+"/"+format+"/"+newFile;
      } catch (IOException e) {
           e.printStackTrace();
           return "fail";
      }
  }
}
  • 使用這個也可以 放回的信息更加詳細

package com.zhang.upload_demo02.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UploadService {
   @Value("${file.uploadLocation}")
   private String uploadLocation;

   public Map<String,Object> upload(MultipartFile multipartFile, String dir){
       try {
           String originalFilename = multipartFile.getOriginalFilename();
           String offlater = originalFilename.substring(originalFilename.lastIndexOf("."));
           String newFile = UUID.randomUUID().toString() + offlater;
           SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
           String timeFile = sdf.format(new Date());
           String serverPath = uploadLocation;
           // F://temp/images   // F://temp/images/
           File targetPath = new File(serverPath+dir,timeFile);
           if (!targetPath.exists()){
               targetPath.mkdirs();
          }
           File targetFile = new File(targetPath,newFile);
           multipartFile.transferTo(targetFile);
           String filename = dir+"/"+timeFile + "/" + newFile;

           Map<String,Object> map = new HashMap<>();
           map.put("url","http://localhost:8777"+"/img/"+filename);
           map.put("name",newFile);
           map.put("suffix",offlater);
           map.put("size",multipartFile.getSize());
           map.put("rpath",dir+"/"+timeFile + "/" + newFile);
           return map;
      } catch (IOException e) {
           e.printStackTrace();
           return null;
      }
  }
}

 

  • Controller層代碼:

package com.zhang.upload_demo01.controller;

import com.zhang.upload_demo01.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
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;

import javax.servlet.http.HttpServletRequest;

@Controller
public class UploadController {

   @Autowired
   private UploadService uploadService;

   @RequestMapping("/")
   public String toIndex(){
       return "upload";  //首頁定位用的
  }
   @PostMapping("/upload/file")
   @ResponseBody
   public String upload(@RequestParam("file")MultipartFile multipartFile, HttpServletRequest request){
       if (multipartFile.isEmpty()){
           return "文件有誤";
      }
       //文件大小
       long size = multipartFile.getSize();
       //文件真實名稱
       String originalFilename = multipartFile.getOriginalFilename();
       //文件類型
       String contentType = multipartFile.getContentType();

       String dir = request.getParameter("dir");
       return uploadService.uploadImag(multipartFile,dir);
  }
}
  • HTML層代碼:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
</head>
<body>
   <form action="/upload/file" method="post" enctype="multipart/form-data">
       <input name="dir" value="images">
       <input name="file" type="file">
       <input type="submit" value="文件上傳">
   </form>
</body>
</html>
  • application.yaml 和 application-dev.yaml 一定要做環境隔離

#服務配置
file:
staticPath: /upload/**
uploadPath: E:/temp/


server:
port: 8080
spring:
profiles:
  active: dev
  • OSS文件上傳 需要去阿里雲申請一下OSS服務

package com.zhang.upload_demo02.service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class OssUploadService {
   public String uploadfile(MultipartFile multipartFile,String dir){
               // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。關於其他Region對應的Endpoint信息,請參見訪問域名和數據中心。
               String endpoint = "oss-cn-beijing.aliyuncs.com";
               // 阿里雲賬號AccessKey擁有所有API的訪問權限,風險很高。強烈建議您創建並使用RAM用戶進行API訪問或日常運維,請登錄RAM控制台創建RAM用戶。
               //LTAI5t73fB85acU8TfeE9io2
               //6Tg0RyOfeyVTebD209Y45O13Bwaoz8
               String accessKeyId = "***";//安全密鑰用戶名
               String accessKeySecret = "***"; //安全密碼
               // 填寫Bucket名稱,例如examplebucket。
               String bucketName = "zitbookings";

               // 創建OSSClient實例。

               OSS ossClient =null;
               try {
                   ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

                   // 1.獲取文件上傳流
                   InputStream inputStream = multipartFile.getInputStream();
                   // 2.構建日期目錄
                   SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                   String dataPath = sdf.format(new Date());
                   // 4.獲取文件真實名字 並重構
                   String originalFilename = multipartFile.getOriginalFilename();
                   String filename = UUID.randomUUID().toString();
                   String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                   String newName = filename + suffix;

                   String fileUrl = dir +"/"+ dataPath + newName;

                   // 5.文件上傳到阿里雲雲服務器
                   ossClient.putObject(bucketName, fileUrl, inputStream);

                   return "http://" +  bucketName + "." + endpoint + "/" + fileUrl;
              } catch (OSSException oe) {
                   System.out.println("Caught an OSSException, which means your request made it to OSS, "
                           + "but was rejected with an error response for some reason.");
                   System.out.println("Error Message:" + oe.getErrorMessage());
                   System.out.println("Error Code:" + oe.getErrorCode());
                   System.out.println("Request ID:" + oe.getRequestId());
                   System.out.println("Host ID:" + oe.getHostId());
                   return "fail";
              } catch (ClientException ce) {
                   System.out.println("Caught an ClientException, which means the client encountered "
                           + "a serious internal problem while trying to communicate with OSS, "
                           + "such as not being able to access the network.");
                   System.out.println("Error Message:" + ce.getMessage());
                   return "fail";
              } catch (IOException e) {
                   e.printStackTrace();
                   return "fail";
              } finally {
                   if (ossClient != null) {
                       ossClient.shutdown();
                  }
              }

  }
}
  • 當然也可以集成一些文本編輯器:WangEditor和WebUpload 這個兩個都可以 仁者見仁

  • WangEditor

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
</head>
<body>
<div id="div1">
   <p>歡迎使用 <b>wangEditor</b> 富文本編輯器</p>
</div>

<!-- 引入 wangEditor.min.js -->
<script src="/editor/wangEditor.min.js"></script>
<script type="text/javascript">
   const E = window.wangEditor;
   const editor = new E('#div1')
   // 或者 const editor = new E( document.getElementById('div1') )
   editor.config.uploadImgServer = '/upload/Oss';
   editor.config.uploadFileName = 'file';
   editor.config.uploadImgParams = {dir: "bbs"};
   editor.config.uploadImgHooks = {
       // 上傳圖片之前
       before: function(xhr) {
          return true;
      },
       // 圖片上傳並返回了結果,圖片插入已成功
       success: function(xhr) {
           console.log('success', xhr)
      },
       // 圖片上傳並返回了結果,但圖片插入時出錯了
       fail: function(xhr, editor, resData) {
           console.log('fail', resData)
      },
       // 上傳圖片出錯,一般為 http 請求的錯誤
       error: function(xhr, editor, resData) {
           console.log('error', xhr, resData)
      },
       // 上傳圖片超時
       timeout: function(xhr) {
           console.log('timeout')
      },
       // 圖片上傳並返回了結果,想要自己把圖片插入到編輯器中
       // 例如服務器端返回的不是 { errno: 0, data: [...] } 這種格式,可使用 customInsert
       customInsert: function(insertImgFn, result) {
           console.log("你上傳的的地址是:",result);
           // result 即服務端返回的接口
           console.log('customInsert', result);
           // insertImgFn 可把圖片插入到編輯器,傳入圖片 src ,執行函數即可
           insertImgFn(result.url);
      }
  }
   editor.create()
</script>
</body>
</html>
  • WebUpload

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <link rel="stylesheet" type="text/css" href="/upload/webuploader.css" />
   <script type="text/javascript" src="/upload/webuploader.js"></script>
   <script type="text/javascript" src="/upload/jquery-3.6.0.js"></script>
</head>
<body>
<!--dom結構部分-->
<div id="uploader-demo">
   <!--用來存放item-->
   <div id="fileList" class="uploader-list"></div>
   <div id="filePicker">選擇圖片</div>
</div>



<script>
   // 初始化Web Uploader
   var uploader = WebUploader.create({

       // 選完文件后,是否自動上傳。
       auto: true,

       // swf文件路徑
       swf: '/upload/Uploader.swf',

       // 文件接收服務端。
       server: '/upload/Oss',

       // 選擇文件的按鈕。可選。
       // 內部根據當前運行是創建,可能是input元素,也可能是flash.
       pick: '#filePicker',

       // 只允許選擇圖片文件。
       accept: {
           title: 'Images',
           extensions: 'gif,jpg,jpeg,bmp,png',
           mimeTypes: 'image/*'
      }
  });
</script>
</body>
</html>

 


免責聲明!

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



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