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

详解SpringBoot文件上传下载和多文件上传(图文)

程序员文章站 2024-03-31 18:36:46
最近在学习springboot,以下是最近学习整理的实现文件上传下载的java代码: 1、开发环境: idea15+ maven+jdk1.8 2、...

最近在学习springboot,以下是最近学习整理的实现文件上传下载的java代码:

1、开发环境:

idea15+ maven+jdk1.8

2、新建一个maven工程:

详解SpringBoot文件上传下载和多文件上传(图文) 

3、工程框架

详解SpringBoot文件上传下载和多文件上传(图文) 

4、pom.xml文件依赖项

<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
 xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelversion>4.0.0</modelversion>
 <groupid>springwebcontent</groupid>
 <artifactid>springwebcontent</artifactid>
 <packaging>war</packaging>
 <version>1.0-snapshot</version>
 <name>springwebcontent maven webapp</name>
 <url>http://maven.apache.org</url>
 <parent>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-parent</artifactid>
  <version>1.4.3.release</version>
 </parent>
 <dependencies>
  <dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-thymeleaf</artifactid>
  </dependency>
  <dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-devtools</artifactid>
   <optional>true</optional>
  </dependency>
  <dependency>
   <groupid>junit</groupid>
   <artifactid>junit</artifactid>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>
 </dependencies>
 <properties>
  <java.version>1.8</java.version>
 </properties>
 <build>
  <finalname>springwebcontent</finalname>
 <plugins>
 <plugin>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-maven-plugin</artifactid>
 </plugin>
</plugins>
 </build>
</project>

5、application.java

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
@springbootapplication
public class application {

  public static void main(string[] args) {
    springapplication.run(application.class, args);
  }
}

6、filecontroller.java

import org.springframework.stereotype.controller;
import org.springframework.ui.model;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.requestparam;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.web.bind.annotation.responsebody;
import org.springframework.web.multipart.multipartfile;
import org.springframework.web.multipart.multiparthttpservletrequest;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.*;
import java.util.list;

@controller
public class filecontroller {
  @requestmapping("/greeting")
  public string greeting(@requestparam(value="name", required=false, defaultvalue="world") string name, model model) {
    model.addattribute("name", name);
    return "greeting";
  }
  private static final logger logger = loggerfactory.getlogger(filecontroller.class);
  //文件上传相关代码
  @requestmapping(value = "upload")
  @responsebody
  public string upload(@requestparam("test") multipartfile file) {
    if (file.isempty()) {
      return "文件为空";
    }
    // 获取文件名
    string filename = file.getoriginalfilename();
    logger.info("上传的文件名为:" + filename);
    // 获取文件的后缀名
    string suffixname = filename.substring(filename.lastindexof("."));
    logger.info("上传的后缀名为:" + suffixname);
    // 文件上传后的路径
    string filepath = "e://test//";
    // 解决中文问题,liunx下中文路径,图片显示问题
    // filename = uuid.randomuuid() + suffixname;
    file dest = new file(filepath + filename);
    // 检测是否存在目录
    if (!dest.getparentfile().exists()) {
      dest.getparentfile().mkdirs();
    }
    try {
      file.transferto(dest);
      return "上传成功";
    } catch (illegalstateexception e) {
      e.printstacktrace();
    } catch (ioexception e) {
      e.printstacktrace();
    }
    return "上传失败";
  }

  //文件下载相关代码
  @requestmapping("/download")
  public string downloadfile(org.apache.catalina.servlet4preview.http.httpservletrequest request, httpservletresponse response){
    string filename = "fileuploadtests.java";
    if (filename != null) {
      //当前是从该工程的web-inf//file//下获取文件(该目录可以在下面一行代码配置)然后下载到c:\\users\\downloads即本机的默认下载的目录
      string realpath = request.getservletcontext().getrealpath(
          "//web-inf//");
      file file = new file(realpath, filename);
      if (file.exists()) {
        response.setcontenttype("application/force-download");// 设置强制下载不打开
        response.addheader("content-disposition",
            "attachment;filename=" + filename);// 设置文件名
        byte[] buffer = new byte[1024];
        fileinputstream fis = null;
        bufferedinputstream bis = null;
        try {
          fis = new fileinputstream(file);
          bis = new bufferedinputstream(fis);
          outputstream os = response.getoutputstream();
          int i = bis.read(buffer);
          while (i != -1) {
            os.write(buffer, 0, i);
            i = bis.read(buffer);
          }
          system.out.println("success");
        } catch (exception e) {
          e.printstacktrace();
        } finally {
          if (bis != null) {
            try {
              bis.close();
            } catch (ioexception e) {
              e.printstacktrace();
            }
          }
          if (fis != null) {
            try {
              fis.close();
            } catch (ioexception e) {
              e.printstacktrace();
            }
          }
        }
      }
    }
    return null;
  }
  //多文件上传
  @requestmapping(value = "/batch/upload", method = requestmethod.post)
  @responsebody
  public string handlefileupload(httpservletrequest request) {
    list<multipartfile> files = ((multiparthttpservletrequest) request)
        .getfiles("file");
    multipartfile file = null;
    bufferedoutputstream stream = null;
    for (int i = 0; i < files.size(); ++i) {
      file = files.get(i);
      if (!file.isempty()) {
        try {
          byte[] bytes = file.getbytes();
          stream = new bufferedoutputstream(new fileoutputstream(
              new file(file.getoriginalfilename())));
          stream.write(bytes);
          stream.close();

        } catch (exception e) {
          stream = null;
          return "you failed to upload " + i + " => "
              + e.getmessage();
        }
      } else {
        return "you failed to upload " + i
            + " because the file was empty.";
      }
    }
    return "upload successful";
  }

7、index.html

<!doctype html>
<html lang="en">
<head>
  <title>getting started: serving web content</title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
<p>get your greeting <a href="/greeting" rel="external nofollow" >here</a></p>
<form action="/upload" method="post" enctype="multipart/form-data">
  文件:<input type="file" name="test"/>
  <input type="submit" />
</form>
<a href="/download" rel="external nofollow" >下载test</a>
<p>多文件上传</p>
<form method="post" enctype="multipart/form-data" action="/batch/upload">
  <p>文件1:<input type="file" name="file" /></p>
  <p>文件2:<input type="file" name="file" /></p>
  <p><input type="submit" value="上传" /></p>
</form>
</html>

完整工程地址:springwebcontent_jb51.rar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。