91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot 文件上傳和下載的實現源碼

發布時間:2020-09-24 21:40:26 來源:腳本之家 閱讀:508 作者:dmfrm 欄目:編程語言

本篇文章介紹SpringBoot的上傳和下載功能。

一、創建SpringBoot工程,添加依賴

compile("org.springframework.boot:spring-boot-starter-web") 
compile("org.springframework.boot:spring-boot-starter-thymeleaf") 

工程目錄為:

SpringBoot 文件上傳和下載的實現源碼

Application.java 啟動類

package hello; 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.boot.context.properties.EnableConfigurationProperties; 
@SpringBootApplication 
public class Application { 
  public static void main(String[] args) { 
    SpringApplication.run(Application.class, args); 
  } 
} 

二、創建測試頁面

在resources/templates目錄下新建uploadForm.html

<html xmlns:th="http://www.thymeleaf.org"> 
<body> 
  <div th:if="${message}"> 
    <h3 th:text="${message}"/> 
  </div> 
  <div> 
    <form method="POST" enctype="multipart/form-data" action="/"> 
      <table> 
        <tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr> 
        <tr><td></td><td><input type="submit" value="Upload" /></td></tr> 
      </table> 
    </form> 
  </div> 
  <div> 
    <ul> 
      <li th:each="file : ${files}"> 
        <a th:href="${file}" rel="external nofollow" th:text="${file}" /> 
      </li> 
    </ul> 
  </div> 
</body> 
</html> 

三、新建StorageService服務

StorageService接口 

package hello.storage; 
import org.springframework.core.io.Resource; 
import org.springframework.web.multipart.MultipartFile; 
import java.nio.file.Path; 
import java.util.stream.Stream; 
public interface StorageService { 
  void init(); 
  void store(MultipartFile file); 
  Stream<Path> loadAll(); 
  Path load(String filename); 
  Resource loadAsResource(String filename); 
  void deleteAll(); 
} 

StorageService實現

package hello.storage; 
import org.springframework.core.io.Resource; 
import org.springframework.core.io.UrlResource; 
import org.springframework.stereotype.Service; 
import org.springframework.util.FileSystemUtils; 
import org.springframework.util.StringUtils; 
import org.springframework.web.multipart.MultipartFile; 
import java.io.IOException; 
import java.net.MalformedURLException; 
import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.nio.file.StandardCopyOption; 
import java.util.function.Predicate; 
import java.util.stream.Stream; 
@Service 
public class FileSystemStorageService implements StorageService 
{ 
  private final Path rootLocation = Paths.get("upload-dir"); 
  /** 
   * 保存文件 
   * 
   * @param file 文件 
   */ 
  @Override 
  public void store(MultipartFile file) 
  { 
    String filename = StringUtils.cleanPath(file.getOriginalFilename()); 
    try 
    { 
      if (file.isEmpty()) 
      { 
        throw new StorageException("Failed to store empty file " + filename); 
      } 
      if (filename.contains("..")) 
      { 
        // This is a security check 
        throw new StorageException("Cannot store file with relative path outside current directory " + filename); 
      } 
      Files.copy(file.getInputStream(), this.rootLocation.resolve(filename), StandardCopyOption.REPLACE_EXISTING); 
    } 
    catch (IOException e) 
    { 
      throw new StorageException("Failed to store file " + filename, e); 
    } 
  } 
  /** 
   * 列出upload-dir下面所有文件 
   * @return 
   */ 
  @Override 
  public Stream<Path> loadAll() 
  { 
    try 
    { 
      return Files.walk(this.rootLocation, 1) //path -> !path.equals(this.rootLocation) 
          .filter(new Predicate<Path>() 
          { 
            @Override 
            public boolean test(Path path) 
            { 
              return !path.equals(rootLocation); 
            } 
          }); 
    } 
    catch (IOException e) 
    { 
      throw new StorageException("Failed to read stored files", e); 
    } 
  } 
  @Override 
  public Path load(String filename) 
  { 
    return rootLocation.resolve(filename); 
  } 
  /** 
   * 獲取文件資源 
   * @param filename 文件名 
   * @return Resource 
   */ 
  @Override 
  public Resource loadAsResource(String filename) 
  { 
    try 
    { 
      Path file = load(filename); 
      Resource resource = new UrlResource(file.toUri()); 
      if (resource.exists() || resource.isReadable()) 
      { 
        return resource; 
      } 
      else 
      { 
        throw new StorageFileNotFoundException("Could not read file: " + filename); 
      } 
    } 
    catch (MalformedURLException e) 
    { 
      throw new StorageFileNotFoundException("Could not read file: " + filename, e); 
    } 
  } 
  /** 
   * 刪除upload-dir目錄所有文件 
   */ 
  @Override 
  public void deleteAll() 
  { 
    FileSystemUtils.deleteRecursively(rootLocation.toFile()); 
  } 
  /** 
   * 初始化 
   */ 
  @Override 
  public void init() 
  { 
    try 
    { 
      Files.createDirectories(rootLocation); 
    } 
    catch (IOException e) 
    { 
      throw new StorageException("Could not initialize storage", e); 
    } 
  } 
} 

StorageException.java

package hello.storage; 
public class StorageException extends RuntimeException { 
  public StorageException(String message) { 
    super(message); 
  } 
  public StorageException(String message, Throwable cause) { 
    super(message, cause); 
  } 
} 
StorageFileNotFoundException.java
package hello.storage; 
public class StorageFileNotFoundException extends StorageException { 
  public StorageFileNotFoundException(String message) { 
    super(message); 
  } 
  public StorageFileNotFoundException(String message, Throwable cause) { 
    super(message, cause); 
  } 
} 

四、Controller創建

將上傳的文件,放到工程的upload-dir目錄,默認在界面上列出可以下載的文件。

listUploadedFiles函數,會列出當前目錄下的所有文件

serveFile下載文件

handleFileUpload上傳文件

package hello;  


import java.io.IOException; 
import java.util.stream.Collectors; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.core.io.Resource; 
import org.springframework.http.HttpHeaders; 
import org.springframework.http.ResponseEntity; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.ExceptionHandler; 
import org.springframework.web.bind.annotation.GetMapping; 
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.ResponseBody; 
import org.springframework.web.multipart.MultipartFile; 
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; 
import org.springframework.web.servlet.mvc.support.RedirectAttributes; 
import hello.storage.StorageFileNotFoundException; 
import hello.storage.StorageService; 
@Controller 
public class FileUploadController { 
  private final StorageService storageService; 
  @Autowired 
  public FileUploadController(StorageService storageService) { 
    this.storageService = storageService; 
  } 
  @GetMapping("/") 
  public String listUploadedFiles(Model model) throws IOException { 
    model.addAttribute("files", storageService.loadAll().map( 
        path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class, 
            "serveFile", path.getFileName().toString()).build().toString()) 
        .collect(Collectors.toList())); 
    return "uploadForm"; 
  } 
  @GetMapping("/files/{filename:.+}") 
  @ResponseBody 
  public ResponseEntity<Resource> serveFile(@PathVariable String filename) { 
    Resource file = storageService.loadAsResource(filename); 
    return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, 
        "attachment; filename=\"" + file.getFilename() + "\"").body(file); 
  } 
  @PostMapping("/") 
  public String handleFileUpload(@RequestParam("file") MultipartFile file, 
      RedirectAttributes redirectAttributes) { 
    storageService.store(file); 
    redirectAttributes.addFlashAttribute("message", 
        "You successfully uploaded " + file.getOriginalFilename() + "!"); 
    return "redirect:/"; 
  } 
  @ExceptionHandler(StorageFileNotFoundException.class) 
  public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) { 
    return ResponseEntity.notFound().build(); 
  } 
} 

源碼下載:https://github.com/HelloKittyNII/SpringBoot/tree/master/SpringBootUploadAndDownload

總結

以上所述是小編給大家介紹的SpringBoot 文件上傳和下載的實現源碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

开化县| 南阳市| 陆良县| 鄂尔多斯市| 七台河市| 富锦市| 霍城县| 宁蒗| 河源市| 汉沽区| 潍坊市| 且末县| 黑龙江省| 独山县| 怀安县| 五河县| 钟山县| 陇川县| 涟水县| 乐山市| 惠州市| 夏津县| 余干县| 福清市| 闵行区| 屏边| 酉阳| 曲水县| 柘城县| 张北县| 江北区| 五常市| 木里| 濮阳市| 镇安县| 灵川县| 信丰县| 中超| 溆浦县| 乌恰县| 扎赉特旗|