Spring Boot文件上傳

spring boot 2.0.5
要實現文件上傳並直接訪問(查看/下載)

配置靜態文件路徑

application.properties

uploadPath=/opt/data1/uploads/
## 上傳路徑設置爲靜態資源路徑,可以通過http直接訪問,比如圖片/pdf會直接顯示在瀏覽器,word/excell會直接下載
spring.resources.static-locations=classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/,file:${uploadPath}

上傳接口

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
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.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件上傳
 *
 * @Author:sahana
 */
@RestController @Slf4j public class UploadController {

  @Value("${uploadPath}") String uploadPath;
  String DIPLOMA = "diploma";
  
  @PostMapping("/upload") public String upload(@PathVariable("id") Integer id,
      @RequestParam("file") MultipartFile file, HttpServletRequest request) {
    if (!file.isEmpty()) {
      try {
        // Get the file and save it somewhere
        byte[] bytes = file.getBytes();
        File dir = new File(uploadPath + File.separator + DIPLOMA + File.separator + id);
        if (!dir.exists())
          dir.mkdirs();
        else {
          FileUtils.deleteDirectory(dir);
          dir.mkdirs();
        }
        //        // 寫文件到服務器
        //        File serverFile = new File(dir.getAbsolutePath()+File.separator+file.getOriginalFilename());
        //        file.transferTo(serverFile);
        Path path = Paths
            .get(uploadPath + DIPLOMA + File.separator + id, file.getOriginalFilename());
        Files.copy(file.getInputStream(), path);
        // String outPath=File.separator + DIPLOMA + File.separator + id + File.separator + file
         //   .getOriginalFilename()
        // 通過 http://{ip}:{port}/{outPath} 能直接訪問資源
        return "上傳成功";
      } catch (IOException e) {
        log.error("")
        return "上傳失敗";
      }
    } else {
      return "空文件";
    }
  }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章