SpringBoot 파일 업로드 다운로드 와 다 중 파일 업로드 에 대한 자세 한 설명(그림)

9687 단어 springboot업로드
최근 SpringBoot 를 배우 고 있 습 니 다.다음은 최근 에 정 리 된 실현 파일 업로드 다운로드 자바 코드 입 니 다.
1.개발 환경:
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(
          "//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
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기