1. 程式人生 > 其它 >關於Spring boot 檔案上傳的檔案

關於Spring boot 檔案上傳的檔案

直接上程式碼

/**

* 1.檔案儲存在伺服器,url地址儲存在資料庫
* 上傳成功之後返回成功儲存的url地址
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public JSONObject upload(@RequestParam("file") MultipartFile file) {
 JSONObject jsonObject = new JSONObject();
    try {

if (file.isEmpty()) {
System.out.println("上傳的檔案為空!");
           jsonObject.put("msg","檔案為空");
        }
// 檔名
String fileName = file.getOriginalFilename();
// 獲取檔案字尾名
String extension = fileName.substring(fileName.indexOf("."));
// 上傳檔案的路徑
String uploadFolder = "C:/home/upload/";
// 生成一個新的檔名
fileName = UUID.randomUUID() + extension;
File dest = new File(uploadFolder + fileName);
// 檢測檔案目錄是否存在 不存在則建立
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();

}
// 返回虛擬檔案訪問路徑
jsonObject.put("fileName",fileName);
jsonObject.put("url","127.0.0.1:8080"+"/專案名稱/upload/"+fileName);

    }
catch (Exception ex)
{
System.out.println("檔案為空");
       jsonObject.put("msg","檔案為空");
    }
   return jsonObject ;
}

/**
* @Description: 上傳檔案路徑對映
* @UpdateRemark: 修改內容
* @Version: 1.0
*/
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class UploadConfig implements WebMvcConfigurer {



/**
* 對映檔案路徑
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**")
.addResourceLocations("file:"+"C:/home/upload/");
    }
}