Java工作笔记-Spring Boot上传图片并显示
发布日期:2021-06-30 10:40:55 浏览次数:2 分类:技术文章

本文共 2582 字,大约阅读时间需要 8 分钟。

目录

 

 


 

 

基本概念

这个是基因Github的一个项目改的,因为页面关闭了,在此找不到了,不能把连接发上来。

这里使用的是FreeMarker。

为了避免重名,使用了UUID生成随机。

找图片文件主要是使用ResourceLoader。

 

代码与实例

程序运行截图如下:

点击选择文件,然后提交:

看看文件夹:

关键源码如下:

application.properties

### FreeMarker 配置spring.freemarker.allow-request-override=false#Enable template caching.启用模板缓存。spring.freemarker.cache=falsespring.freemarker.check-template-location=truespring.freemarker.charset=UTF-8spring.freemarker.content-type=text/htmlspring.freemarker.expose-request-attributes=falsespring.freemarker.expose-session-attributes=falsespring.freemarker.expose-spring-macro-helpers=false#设置面板后缀spring.freemarker.suffix=.ftl# 设置单个文件最大内存multipart.maxFileSize=50Mb# 设置所有文件最大内存multipart.maxRequestSize=50Mb# 自定义文件上传路径web.upload-path=F:/SpringTest/

TestController.java

package com.example.demo.controller;import com.example.demo.util.FileUtils;import org.springframework.beans.factory.annotation.Value;import org.springframework.core.io.ResourceLoader;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;import java.util.Map;@Controllerpublic class TestController {    private final ResourceLoader resourceLoader;    public TestController(ResourceLoader resourceLoader) {        this.resourceLoader = resourceLoader;    }    @Value("${web.upload-path}")    private String path;    @RequestMapping("test")    private String toUpload(){        return "test";    }    //上传文件    @RequestMapping("fileUpload")    public String upload(@RequestParam("fileName") MultipartFile file, Map
map){ String localPath = "F:/SpringTest"; String msg = ""; StringBuffer newName = new StringBuffer(); if(FileUtils.upload(file, localPath, file.getOriginalFilename(), newName)){ msg = "上传成功"; } else{ msg = "上传失败"; } newName.toString(); map.put("msg", msg); //map.put("fileName", file.getOriginalFilename()); map.put("fileName", newName.toString()); return "forward:/test"; } //显示单张图片 @RequestMapping("show") public ResponseEntity showPhotos(String fileName){ if(fileName == null){ return ResponseEntity.notFound().build(); } try{ return ResponseEntity.ok(resourceLoader.getResource("file:" + path + fileName)); } catch (Exception e){ return ResponseEntity.notFound().build(); } }}

 

 

源码打包下载

地址如下:

转载地址:https://it1995.blog.csdn.net/article/details/103385609 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Java工作笔记-@Value注解的使用(可用于配置文件)
下一篇:Java工作笔记-Java函数参传值传引用问题

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月30日 05时13分20秒