亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

詳解SpringBoot文件上傳下載和多文件上傳(圖文)

 更新時間:2017年02月27日 11:26:07   作者:Coding13  
本篇文章主要介紹了詳解SpringBoot文件上傳下載和多文件上傳(圖文),具有一定的參考價值,感興趣的小伙伴們可以參考一下。

最近在學習SpringBoot,以下是最近學習整理的實現(xiàn)文件上傳下載的Java代碼:

1、開發(fā)環(huán)境:

IDEA15+ Maven+JDK1.8

2、新建一個maven工程:

這里寫圖片描述 

3、工程框架

這里寫圖片描述 

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(
          "http://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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • java實現(xiàn)飯店點菜系統(tǒng)

    java實現(xiàn)飯店點菜系統(tǒng)

    這篇文章主要為大家詳細介紹了java實現(xiàn)飯店點菜系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • SpringBoot如何使用mail實現(xiàn)登錄郵箱驗證

    SpringBoot如何使用mail實現(xiàn)登錄郵箱驗證

    在實際的開發(fā)當中,不少的場景中需要我們使用更加安全的認證方式,同時也為了防止一些用戶惡意注冊,我們可能會需要用戶使用一些可以證明個人身份的注冊方式,如短信驗證、郵箱驗證等,這篇文章主要介紹了SpringBoot如何使用mail實現(xiàn)登錄郵箱驗證,需要的朋友可以參考下
    2024-06-06
  • 使用XSD校驗Mybatis的SqlMapper配置文件的方法(1)

    使用XSD校驗Mybatis的SqlMapper配置文件的方法(1)

    這篇文章以前面對SqlSessionFactoryBean的重構為基礎,簡單的介紹了相關操作知識,然后在給大家分享使用XSD校驗Mybatis的SqlMapper配置文件的方法,感興趣的朋友參考下吧
    2016-11-11
  • MyBatis注解實現(xiàn)動態(tài)SQL問題

    MyBatis注解實現(xiàn)動態(tài)SQL問題

    這篇文章主要介紹了MyBatis注解實現(xiàn)動態(tài)SQL問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • 淺談JAVA 類加載器

    淺談JAVA 類加載器

    這篇文章主要介紹了JAVA 類加載器的的相關資料,文中示例代碼非常詳細,幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-06-06
  • 詳解如何實現(xiàn)OpenAPI開發(fā)動態(tài)處理接口的返回數(shù)據

    詳解如何實現(xiàn)OpenAPI開發(fā)動態(tài)處理接口的返回數(shù)據

    這篇文章主要為大家介紹了OpenAPI開發(fā)動態(tài)處理接口的返回數(shù)據如何實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-04-04
  • Java開發(fā)實現(xiàn)人機猜拳游戲

    Java開發(fā)實現(xiàn)人機猜拳游戲

    這篇文章主要為大家詳細介紹了Java開發(fā)實現(xiàn)人機猜拳游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-08-08
  • Java Web監(jiān)聽器如何實現(xiàn)定時發(fā)送郵件

    Java Web監(jiān)聽器如何實現(xiàn)定時發(fā)送郵件

    這篇文章主要介紹了Java Web監(jiān)聽器如何實現(xiàn)定時發(fā)送郵件,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-12-12
  • Java 中 Reference用法詳解

    Java 中 Reference用法詳解

    這篇文章主要介紹了Java 中 Reference用法詳解的相關資料,需要的朋友可以參考下
    2017-03-03
  • java中join方法的理解與說明詳解

    java中join方法的理解與說明詳解

    這篇文章主要給大家介紹了關于java中join方法的理解與說明的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-01-01

最新評論