1. 程式人生 > 其它 >Spring Boot檔案上傳

Spring Boot檔案上傳

說明:Spring Boot應用中如何實現檔案上傳功能

1.建立專案,匯入依賴

<?xml version="1.0" encoding="UTF-8"?>
<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>com.zslaa</groupId> <artifactId>springboot_fileupload</artifactId> <version>1.0-SNAPSHOT</version> <!-- 匯入springboot父工程. 注意:任何的SpringBoot工程都必須有的!!! --> <!-- 父工程的作用:鎖定起步的依賴的版本號,並沒有真正到依賴 --
> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.11.RELEASE</version> </parent> <dependencies> <!--web起步依賴--> <dependency>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 匯入thymeleaf座標 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> </project>

2.設計上傳頁面

在這裡插入圖片描述

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>檔案上傳頁面</title>
</head>
<body>
檔案上傳頁面

<hr/>
<form action="/uploadAttach" method="post" enctype="multipart/form-data">
	請選擇檔案:<input type="file" name="attach"/><br/>
	<input type="submit" value="開始上傳"/>
</form>
</body>
</html>

3.編寫Controller處理檔案

package com.zslaa.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 控制器
 */
@RestController
public class UploadController {
	/*
	 * 接收檔案
	 */
	@RequestMapping("/uploadAttach")
	public String upload(@RequestParam("attach")MultipartFile file) throws Exception{
		//處理檔案
		System.out.println("檔案原名稱:"+file.getOriginalFilename());
		System.out.println("檔案型別:"+file.getContentType());
		
		//儲存到硬碟
		file.transferTo(new File("c:/"+file.getOriginalFilename()));

		return "上傳成功";
	} 
}

4.編寫引導類

package com.yiidian;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Spring Boot引導類
 * 一點教程網 - www.yiidian.com
 */
@SpringBootApplication
public class MyBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyBootApplication.class,args);
    }

}

5.執行測試

在這裡插入圖片描述
在這裡插入圖片描述