文件上傳方式
-
直接上傳到應用服務器
-
上傳到oss(阿里云静尼,七牛云)
-
前端將圖片轉成Base64編碼上傳
上傳服務器的一個例子
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/*
* 上傳文件控制器
* 直接上傳到服務器
* 2019.3.25
* */
@Controller
public class UploadController {
SimpleDateFormat YYY = new SimpleDateFormat("yyyy-MM-dd");
@GetMapping("/")
public String index(){
return "upload";
}
@PostMapping("/upload")
public String fileUpload(@RequestParam("file")MultipartFile srcFile, RedirectAttributes redirectAttributes){
//前端沒有選擇文件鼠渺,srcFile為空
if(srcFile.isEmpty()){
redirectAttributes.addFlashAttribute("message","請選擇一個文件");
return "redirect:upload_status";
}
//選擇了文件拦盹,開始進行上傳操作
try{
//構建上傳目標路徑
File destFile=new File(ResourceUtils.getURL("classpath:").getPath());
if(!destFile.exists()){
destFile=new File("");
}
//輸出目標文件的絕對路徑
System.out.println("file path:"+destFile.getAbsolutePath());
File upload=new File(destFile.getAbsolutePath(),YYY.format(new Date())+"/");
//拼接static目錄
String fileName= srcFile.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
fileName= UUID.randomUUID() +suffixName;
//若目標文件夾不存在溪椎,則創(chuàng)建一個
if(!upload.exists()){
upload.mkdirs();
}
System.out.println("完整的上傳路徑:"+upload.getAbsolutePath()+"/"+srcFile.getOriginalFilename());
//根據(jù)srcFile的大小,準備一個字節(jié)數(shù)組
byte[] bytes=srcFile.getBytes();
//拼接上傳路徑
/*Path path= Paths.get(UPLOAD_FOLDER+srcFile.getOriginalFilename());*/
//通過項目路徑沼侣,拼接上傳路徑
Path path=Paths.get(upload.getAbsolutePath()+"/"+srcFile.getOriginalFilename());
//最重要的一步歉秫,將源文件寫入目標地址
Files.write(path,bytes);
//將文件上傳成功的信息寫入messages
redirectAttributes.addFlashAttribute("message","文件上傳成功"+srcFile.getOriginalFilename());
}catch (IOException e){
e.printStackTrace();
}
return "redirect:upload_status";
}
//匹配
@GetMapping("/upload_status")
public String uploadStatusPage(){
return "upload_status";
}
}
<title>Spring Boot 文件上傳頁面</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上傳">
</form>
<title>文件上傳狀態(tài)顯示</title>
</head>
<body>
<h2>Spring Boot的文件上傳狀態(tài)</h2>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>