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>


结果图:


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。