spring文件上傳大小限制「spring文件上傳怎麼實現」

Spring Boot或Spring Cloud快速實現文件上傳

很多時候我們都需要在Spring Boot或Spring Cloud中快速集成文件上傳功能,但是對於新手來說增加文件上傳功能需要查閱很多文檔。這裡給出了示例可以幫助您快速將文件上傳功能集成到系統中來。

第一步,我們需要在application.yml中配置文件上傳的大小

spring:
  servlet:
    multipart:
      max-file-size: 1500MB
      max-request-size: 1500MB

第二步,為了能快速處理文件名和URL,我們要用到FilenameUtils,在pom.xml的dependencies中引入Apache Commons IO,注意是否已經有引用,避免版本衝突

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

第三步,寫一個Controller,處理文件上傳的請求

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上傳控制器
 *
 * @author 楊若瑜
 */
@RestController
@RequestMapping("/platform/")
public class UploadFileController {
 
    // 相對於項目根路徑的上傳路徑
    private static final String UPLOAD_FOLDER = "/upload/";
    // 返回給前端的服務器根路徑(分布式、CDN場景很有用)
    private static final String URL_SERVER = "http://127.0.0.1:8080/";
    // 允許上傳的文件擴展名
    private static final String[] ALLOW_EXTENSIONS = new String[]{
 
            // 圖片
            "jpg", "jpeg", "png", "gif", "bmp",
            // 壓縮包
            "zip", "rar", "gz", "7z", "cab",
            // 音視頻,
            "wav", "avi", "mp4", "mp3", "m3u8", "ogg", "wma", "wmv", "rm", "rmvb", "aac", "mov", "asf", "flv",
            // 文檔
            "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pot", "txt", "csv", "md", "pdf"
    };

    /**
     * 判斷文件名是否允許上傳
     * @param fileName 文件名
     * @return
     */
    public boolean isAllow(String fileName) {
 
        String ext = FilenameUtils.getExtension(fileName).toLowerCase();
        for (String allowExtension : ALLOW_EXTENSIONS) {
 
            if (allowExtension.toLowerCase().equals(ext)) {
 
                return true;
            }
        }
        return false;
    }

    /**
     * 上傳文件
     * @param request 請求
     * @param file 文件,與前台提交表單的file相一致
     * @return 返回JSON
     */
    @RequestMapping("upload")
    public Object upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
 
        String webAppFolder = request.getServletContext().getRealPath("/");

        String fileName = file.getOriginalFilename();
        if (isAllow(fileName)) {
 
            String ext = FilenameUtils.getExtension(fileName).toLowerCase();
            String newFileName = UUID.randomUUID().toString().replace("-", "");
            // 自動創建上傳目錄
            String targetPath = FilenameUtils.normalize(webAppFolder + "/" + UPLOAD_FOLDER);
            String targetFile = FilenameUtils.normalize(targetPath + "/" + newFileName + "." + ext);
            new File(targetPath).mkdirs();

            try {
 
                String urlPath = URL_SERVER + "/" + UPLOAD_FOLDER + "/" + newFileName + "." + ext;
                file.transferTo(new File(targetFile));
                Map<String, Object> resJson = new LinkedHashMap<>();
                resJson.put("status", "success");
                resJson.put("data", FilenameUtils.normalize(urlPath,true).replace("http:/","http://").replace("https:/","https://"));
                return resJson;
            } catch (Exception e) {
 
                e.printStackTrace();
                Map<String, Object> resJson = new LinkedHashMap<>();
                resJson.put("status", "error");
                resJson.put("message", "文件上傳失敗:" + e.getMessage());
                return resJson;
            }

        } else {
 
            Map<String, Object> resJson = new LinkedHashMap<>();
            resJson.put("status", "error");
            resJson.put("message", "該類型文件不允許上傳");
            return resJson;
        }
    }
}

第四步、寫一個測試網頁upload.html,啟動並測試一下是否好用。

<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>上傳文件測試</title>
</head>
<body>
    <form action="/platform/upload" method="post" enctype="multipart/form-data">
        請選擇文件:<input type="file" name="file"><br>
        <input type="submit" value="上傳">
    </form>
</body>
</html>

選擇一張照片,上傳

Spring Boot或Spring Cloud快速實現文件上傳

此時後台會返回一個JSON,我們打開data所指向的圖片看看是否上傳成功:

Spring Boot或Spring Cloud快速實現文件上傳

果然,圖片已經上傳成功

Spring Boot或Spring Cloud快速實現文件上傳

至此,如何使用Spring Boot或Spring Cloud實現文件上傳功能就寫到這裡。最後需要補充的是,如果你的使用場景使用ajax或App上傳,表單提交類型必須為multipart/form-data,並且以post的方式提交。

這裡放上jQuery的範例:

// userInfoAvatar是一個input,並且type為file
var file = document.getElementById('userInfoAvatar').files[0];
var formData = new FormData();
formData.append("file",file);
$.ajax({
 
  type: 'POST',
  url: '/platform/upload',
  data: formData,
  contentType: false,
  processData: false,
  dataType: "json",
  mimeType: "multipart/form-data",
  success: function(data) {
 
          // 成功時回調
  },    
  error : function(data){
 
  		  // 失敗時回調
   }
});

放上axios範例:

// userInfoAvatar是一個input,並且type為file
let file = document.getElementById('userInfoAvatar').files[0];
let formData = new FormData();
formData.append("file",file);
axios({
 
	method: 'POST',
	url: '/platform/upload',
	data:formData,
	headers: {
 
		'Content-Type': 'multipart/form-data'
	}
})
.then((data)=>{
 
	console.log(data)
})
.catch((ex)=>{
 
	console.error(ex)
})

放上Http Client Fluent API範例:

String fileName = 文件名;
byte[] bytes = 文件的二進制;

MultipartEntityBuilder builder = MultipartEntityBuilder.create()
        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        .setCharset(Charset.forName("utf-8"));
builder.addBinaryBody("file", bytes, ContentType.MULTIPART_FORM_DATA, fileName); 

String responseJson = Request.Post("http://127.0.0.1:8080/platform/upload")
        .connectTimeout(20000)
        .socketTimeout(20000)
        .body(builder.build())
        .execute().returnContent().asString();

System.out.println(responseJson);

其他的框架如法炮製即可。真正放到正式環境之前記得要加強安全防護,對用戶進行鑒權。

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/205484.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-07 17:47
下一篇 2024-12-07 17:47

相關推薦

發表回復

登錄後才能評論