Spring Boot 上传文件(spring boot upload file)

Spring Boot 上传文件(spring boot upload file)

本篇文章将说明在Spring Boot web程序中如何上传文件。

Uploading Files

https://spring.io/guides/gs/uploading-files/

开发环境:

1. eclipse Oxygen Release (4.7.0)

2. Spring Boot 1.4.3 RELEASE

3. Spring 4.3.5 RELEASE

4. Thymelaef

5. Maven

6. Embedded Tomcat 8

1.最终的项目结构

2.项目所需依赖 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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
 
  <groupId>org.thinkingingis</groupId>
  <artifactId>spring-boot-fileupload</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
 
  <name>spring-boot-fileupload</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>
 
  <properties>
    <java.version>1.8</java.version>
  </properties>
 
  <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>
 
  </dependencies>
  
  
  <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  
</project>

3. UploadController.java
用MultipartFile类去匹配上传的文件

package org.thinkingingis.controller;
 
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
 
@Controller
public class UploadController {
    
    private static String UPLOAD_FOLDER = "H://temp//";
    
    @GetMapping("/")
    public String index() {
        return "upload";
    }
    
    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        if(file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "请选择一个上传文件");
        }
        
        try {
            
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);
            redirectAttributes.addFlashAttribute("message", "已经将 '" + file.getOriginalFilename() + "' 的文件上传成功");
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return "redirect:/uploadStatus";
    }
    
    @GetMapping("/uploadStatus")
    public String uploadStatus() {
        return "uploadStatus";
    }
    
}

4. Thymeleaf 前端页面
4.1 upload.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
 
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
</head>
 
<body>
 
<h1>ThinkingInGIS</h1> <br/>
 
<h1>Spring Boot 文件上传示例</h1>
 
<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="上传" />
</form>
 
</body>
</html>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 和 Vue 中实现文件上传,可以按照以下步骤进行: 1. 在 Vue 中创建一个文件上传表单,代码如下: ``` <template> <div> <form> <input type="file" ref="fileInput"> <button type="button" @click="uploadFile">上传</button> </form> </div> </template> <script> export default { methods: { uploadFile() { let file = this.$refs.fileInput.files[0]; let formData = new FormData(); formData.append("file", file); // 发送文件到后端 } } } </script> ``` 2. 在 Spring Boot 中创建一个文件上传接口,代码如下: ``` @RestController public class FileUploadController { @PostMapping("/upload") public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) { try { String fileName = file.getOriginalFilename(); Path path = Paths.get("/uploads/" + fileName); Files.write(path, file.getBytes()); return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK); } catch (IOException e) { e.printStackTrace(); return new ResponseEntity<>("Failed to upload file", HttpStatus.INTERNAL_SERVER_ERROR); } } } ``` 3. 在 Vue 中使用 `axios` 发送文件到后端,代码如下: ``` <template> <div> <form> <input type="file" ref="fileInput"> <button type="button" @click="uploadFile">上传</button> </form> </div> </template> <script> import axios from 'axios'; export default { methods: { uploadFile() { let file = this.$refs.fileInput.files[0]; let formData = new FormData(); formData.append("file", file); axios.post("/upload", formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(response => { console.log(response.data); }).catch(error => { console.log(error); }); } } } </script> ``` 以上就是在 Spring Boot 和 Vue 中实现文件上传的步骤。注意,在 Spring Boot 中需要在 `application.properties` 中配置文件上传路径,例如: ``` spring.servlet.multipart.enabled=true spring.servlet.multipart.file-size-threshold=2KB spring.servlet.multipart.max-file-size=200MB spring.servlet.multipart.max-request-size=215MB spring.servlet.multipart.location=/uploads/ ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值