1. 程式人生 > >springboot(六):spingboot如何實現檔案上傳

springboot(六):spingboot如何實現檔案上傳

最近一直在忙事情,有段時間沒有發教程了,在這裡說聲抱歉,

不過關於springboot的jaio教程我還是會更新完整的,那就開始今天的內容

今天要講的是檔案的上傳用法,直接來例子講解:

1、首先去寫一個簡單的頁面file.html,可以觸發就行,程式碼如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<!-- 單個檔案上傳 -->
	<form action="/upload" method="POST" enctype="multipart/form-data">
		檔案:<input type="file" name="test" /> <input type="submit" />
	</form>
	<!--將查詢到的資料新增到xls檔案中,並下載 -->
	<a href="/UserExcelDownloads">下載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>
</body>
</html>

2、建立一個FileController.java,此類中寫的是檔案上傳的業務程式碼

package com.test.controller;

import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
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.multipart.MultipartFile;

@Controller
public class FileController2 {
	
	private static final Logger logger = LoggerFactory.getLogger(FileController2.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 "上傳失敗";
	}
}

3、上面兩步驟wan'完成以後,然後你就直接去訪問file.html頁面,

       然後直接點選上傳ti'j提交就可以看到到效果了

4、如果使用本人自己的專案,訪問地址如下:

      http://localhost:8090/login  UserName:admin  UserPassword:12345

GitHub原始碼地址:https://github.com/APassionMy/github.springboot-two

上一篇:springboot(五) spingboot整合jpa