最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot 文件上傳和下載的實(shí)現(xiàn)源碼

 更新時(shí)間:2018年04月02日 10:18:09   作者:dmfrm  
這篇文章主要介紹了SpringBoot 文件上傳和下載的實(shí)現(xiàn)源碼,代碼簡(jiǎn)單易懂非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下

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

一、創(chuàng)建SpringBoot工程,添加依賴

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

工程目錄為:

Application.java 啟動(dòng)類

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); 
  } 
} 

二、創(chuàng)建測(cè)試頁面

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

<html xmlns:th="http://www.thymeleaf.org"> 
<body> 
  <div th:if="${message}"> 
    <h2 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服務(wù)

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實(shí)現(xiàn)

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創(chuàng)建

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

listUploadedFiles函數(shù),會(huì)列出當(dāng)前目錄下的所有文件

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

總結(jié)

以上所述是小編給大家介紹的SpringBoot 文件上傳和下載的實(shí)現(xiàn)源碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

  • 解析Flink內(nèi)核原理與實(shí)現(xiàn)核心抽象

    解析Flink內(nèi)核原理與實(shí)現(xiàn)核心抽象

    Flink API提供了開發(fā)的接口,此外,為了實(shí)現(xiàn)業(yè)務(wù)邏輯,還必須為開發(fā)者提供自定義業(yè)務(wù)邏輯的能力,下面為大家解析Flink內(nèi)核原理與實(shí)現(xiàn)核心抽象
    2021-08-08
  • Java多線程之FutureTask的介紹及使用

    Java多線程之FutureTask的介紹及使用

    之前介紹了線程池相關(guān)的對(duì)象,Runable Callable與Future,下面介紹FutureTask的作用,它的特性是怎樣的呢,需要的朋友可以參考下
    2021-06-06
  • ?Java圖形化界面編程實(shí)現(xiàn)簡(jiǎn)單計(jì)算器

    ?Java圖形化界面編程實(shí)現(xiàn)簡(jiǎn)單計(jì)算器

    這篇文章主要介紹了Java圖形化界面編程實(shí)現(xiàn)簡(jiǎn)單計(jì)算器,下面文章圍繞Java圖形化界面編程實(shí)現(xiàn)簡(jiǎn)單計(jì)算器的相關(guān)資料展開詳細(xì)內(nèi)容,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-01-01
  • Java開發(fā)過程中關(guān)于異常處理的詳解

    Java開發(fā)過程中關(guān)于異常處理的詳解

    異常是程序中的一些錯(cuò)誤,但不是所有錯(cuò)誤都是異常,且錯(cuò)誤有時(shí)候是可以避免的。比如說,你的代碼少一個(gè)分號(hào),那運(yùn)行出來結(jié)果是提示是錯(cuò)誤 java.lang.Error;如果你用System.out.println(11/0),那么你是因?yàn)槟阌?做了除數(shù),會(huì)拋出 java.lang.ArithmeticException 的異常
    2021-10-10
  • Java中的CyclicBarrier循環(huán)柵欄深入解析

    Java中的CyclicBarrier循環(huán)柵欄深入解析

    這篇文章主要介紹了Java中的CyclicBarrier循環(huán)柵欄深入解析,CycleBarrier 它就相當(dāng)于是一個(gè)柵欄,所有線程在到達(dá)柵欄后都需要等待其他線程,等所有線程都到達(dá)后,再一起通過,需要的朋友可以參考下
    2023-12-12
  • 在IDEA中 實(shí)現(xiàn)給main方法附帶參數(shù)的操作

    在IDEA中 實(shí)現(xiàn)給main方法附帶參數(shù)的操作

    這篇文章主要介紹了在IDEA中 實(shí)現(xiàn)給main方法附帶參數(shù)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-01-01
  • spring boot日志管理配置

    spring boot日志管理配置

    這篇文章主要介紹了spring boot日志管理配置的相關(guān)資料,需要的朋友可以參考下
    2017-04-04
  • java.lang.Void類源碼解析

    java.lang.Void類源碼解析

    這篇文章主要介紹了java.lang.Void類源碼解析的相關(guān)內(nèi)容,對(duì)源碼中的部分內(nèi)容進(jìn)行解釋,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-10-10
  • Flink部署集群整體架構(gòu)源碼分析

    Flink部署集群整體架構(gòu)源碼分析

    這篇文章主要為大家介紹了Flink部署集群及整體架構(gòu)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-12-12
  • Elasticsearch索引庫和文檔的相關(guān)操作詳細(xì)指南

    Elasticsearch索引庫和文檔的相關(guān)操作詳細(xì)指南

    這篇文章主要給大家介紹了關(guān)于Elasticsearch索引庫和文檔的相關(guān)操作的相關(guān)資料,Elasticsearch是用Java開發(fā)并且是當(dāng)前最流行的開源的企業(yè)級(jí)搜索引擎,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-11-11

最新評(píng)論

昭苏县| 双鸭山市| 个旧市| 遂川县| 钟祥市| 洪泽县| 务川| 公安县| 集贤县| 彰化市| 宝应县| 武冈市| 鲁甸县| 怀仁县| 武夷山市| 万山特区| 修水县| 祁门县| 芜湖市| 淮滨县| 张家界市| 黄陵县| 锦州市| 萝北县| 西畴县| 南阳市| 三明市| 舟曲县| 页游| 张家川| 青海省| 文水县| 五台县| 新宾| 潼关县| 友谊县| 兴安县| 青州市| 苏尼特左旗| 稻城县| 综艺|