springboot實現圖片文件上傳

application配置:

server.port=8899

file.upload.path=F://images/

file.upload.path.relative=/images/**

spring.thymeleaf.prefix=classpath:/templates/


后臺代碼

package com.example.controller;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;

import java.io.IOException;

@Controller

public class TestController {

/**上傳地址*/

? ? @Value("${file.upload.path}")

private StringfilePath;

? ? // 跳轉上傳頁面

? ? @RequestMapping("test")

public Stringtest() {

return "Page";

? ? }

// 執行上傳

/* @RequestMapping("upload")

public String upload(@RequestParam("file") MultipartFile file, Model model) {

// 獲取上傳文件名

String filename = file.getOriginalFilename();

// 定義上傳文件保存路徑

String path = filePath+"rotPhoto/";

// 新建文件

File filepath = new File(path, filename);

// 判斷路徑是否存在,如果不存在就創建一個

if (!filepath.getParentFile().exists()) {

filepath.getParentFile().mkdirs();

}

try {

// 寫入文件

file.transferTo(new File(path + File.separator + filename));

} catch (IOException e) {

e.printStackTrace();

}

// 將src路徑發送至html頁面

model.addAttribute("filename", "/images/rotPhoto/"+filename);

return "Page";

}*/

}


頁面代碼

<!DOCTYPE html>

<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">

? ? <meta charset="UTF-8">

? ? <link rel="stylesheet" href="../css/bootstrap.css">

? ? <title>Title

<form action="../upload" method="post" enctype="multipart/form-data">

? ? <input type="file" name="file" accept="image/*">


? ? <input type="submit" value="上傳" class="btn btn-success">

[[${filename}]]


<img th:src="@{${filename}}" alt="圖片">

</html>


結果圖:


?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。