欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot 文件上传和下载的实现源码

程序员文章站 2023-08-13 21:45:56
本篇文章介绍springboot的上传和下载功能。 一、创建springboot工程,添加依赖 compile("org.springframework.boo...

本篇文章介绍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}"> 
    <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服务

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 文件上传和下载的实现源码,希望对大家有所帮助