Springboot上传图片并访问
Springboot上传图片并访问
步骤
配置绝对路径,并将这个绝对路径添加到springboot静态资源目录中。
文件上传使用绝对路径保存。返回web相对路径,前端加上域名和项目路径,生成完整的路径。
注意如果路径不是绝对路径,则transfer方法实现会自动加上默认基础路径。
webappfile:
#文件上传目录(注意Linux和Windows上的绝对路径不同,不能通用。)
# uploadPath: E:/image/upload/
uploadPath: /root/sources${server.servlet.context-path}/image/upload/
spring:
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/, file:${webappfile.uploadPath}
server:
port: 80
servlet:
context-path: /mozq
打印日志
webPath=account/img
webFilePath=account/img/Snipaste_2019-06-24_15-46-57.png
filePath=/root/sources/mozq/image/upload/account/img/Snipaste_2019-06-24_15-46-57.png
uploadReal,destFile=/root/sources/mozq/image/upload/account/img/Snipaste_2019-06-24_15-46-57.png
uploadReal,destFile.getParentFile=/root/sources/mozq/image/upload/account/img
Controller
package com.mozq.boot.upload01.demo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
@RestController
public class UploadController {
@Autowired
private FileService fileService;
@Value("${webappfile.uploadPath}")
private String uploadPath;
@RequestMapping("/uploadNew")
public String uploadNew(@RequestParam("img")MultipartFile imgFile, HttpServletRequest request) throws IOException {
String webPath = "account/img";
System.out.println("webPath=" + webPath);
String webFilePath = PathUtil.appendWebPath(webPath, imgFile.getOriginalFilename());
System.out.println("webFilePath=" + webFilePath);
String filePath = PathUtil.appendWebPath(uploadPath, webFilePath);
System.out.println("filePath=" + filePath);
Map<String, String> result = fileService.uploadReal(filePath, imgFile);
result.put("webUrl", webFilePath);
return JSONObject.toJSONString(result);
}
}
FileService
public Map<String, String> uploadReal(String fileName, MultipartFile file){
//处理后缀
HashMap<String, String> result = new HashMap<>();
//获取物理路径
File destFile = new File(fileName);
System.out.println("uploadReal,destFile=" + destFile.getAbsolutePath());
System.out.println("uploadReal,destFile.getParentFile=" + destFile.getParentFile().getAbsolutePath());
//目录不存在
if(!destFile.getParentFile().exists()){
destFile.getParentFile().mkdirs();
}
//目录存在是文件
if(destFile.getParentFile().isFile()){
result.put("flag", "fail");
result.put("message","父级路径是文件而不是目录");
return result;
}
//文件已经存在
/*if(destFile.exists()){
result.put("flag", "fail");
result.put("message","文件已经存在");
return result;
}*/
try {
file.transferTo(destFile);
result.put("flag", "success");
result.put("message","文件上传成功");
} catch (IOException e) {
e.printStackTrace();
result.put("flag", "fail");
result.put("message","文件写入本地发生异常");
}
return result;
}
PathUtil
package com.mozq.boot.upload01.demo;
import java.io.File;
public class PathUtil {
public static String appendPathSep(String src, String separator, String... addPaths){
StringBuilder result = new StringBuilder(src);
for (int i = 0; i < addPaths.length; i++) {
String temp = addPaths[i].startsWith(separator)? addPaths[i] : separator + addPaths[i];
if(result.toString().endsWith(separator)){
//含头不含尾。
result.delete(result.length() - separator.length(), result.length());
}
result.append(temp);
}
return result.toString();
}
public static String appendWebPath(String src,String... addPaths){
return appendPathSep(src, "/", addPaths);
}
public static String appendPath(String src, String... addPaths){
return appendPathSep(src, File.separator, addPaths);
}
public static boolean startWith(String src, String[] sep){
for (String s : sep) {
if(src.startsWith(s)){
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(PathUtil.startWith("jie",new String[]{"/"}));
System.out.println(PathUtil.startWith("/jie",new String[]{"\\"}));
System.out.println(PathUtil.startWith("\\jie",new String[]{"\\","/"}));
// String s = PathUtil.appendPathSep("acount/", "/","/jie/chagn", "/xie/aaa/");
// System.out.println(s);
/*StringBuilder sb = new StringBuilder("mozq/account/img/");
sb.delete(sb.length() - 2 , sb.length() - 1);
System.out.println(sb.toString());*/
// StringBuilder sb = new StringBuilder("mozq/account/img/");
// sb.delete(-2, -3);//Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2
//System.out.println(null + "123");
//StringBuilder stringBuilder = new StringBuilder(null);
//Exception in thread "main" java.lang.NullPointerException
}
}
Springboot上传图片并访问的更多相关文章
- 六、SpringBoot与数据访问
六.SpringBoot与数据访问 1.JDBC spring: datasource: username: root password: 123456 url: jdbc:mysql://192.1 ...
- (转)SpringBoot非官方教程 | 第三篇:SpringBoot用JdbcTemplates访问Mysql
本文介绍springboot通过jdbc访问关系型MySQL,通过spring的JdbcTemplate去访问. 准备工作 jdk 1.8 maven 3.0 idea mysql 初始化mysql: ...
- SpringBoot非官方教程 | 第三篇:SpringBoot用JdbcTemplates访问Mysql
转载请标明出处: 原文首发于https://www.fangzhipeng.com/springboot/2017/07/11/springboot3-JdbcTemplates-Mysql/ 本文出 ...
- 第三篇:SpringBoot用JdbcTemplates访问Mysql
本文介绍springboot通过jdbc访问关系型mysql,通过spring的JdbcTemplate去访问. 准备工作 jdk 1.8 maven 3.0 idea mysql 初始化mysql: ...
- https://segmentfault.com/a/1190000012844836---------关于SpringBoot上传图片的几种方式
关于SpringBoot上传图片的几种方式 https://segmentfault.com/a/1190000012844836
- springboot 静态资源访问,和文件上传 ,以及路径问题
springboot 静态资源访问: 这是springboot 默认的静态资源访问路径 访问顺序依次从前到后(http://localhost:8080/bb.jpg) spring.resourc ...
- SpringBoot之数据访问和事务-专题三
SpringBoot之数据访问和事务-专题三 四.数据访问 4.1.springboot整合使用JdbcTemplate 4.1.1 pom文件引入 <parent> <groupI ...
- 解决springboot项目打成jar包部署到linux服务器后上传图片无法访问的问题
前言:目前大三,自己也在学习和摸索的阶段.在和学校的同学一起做前后端分离项目的时候,我们发现将后端打包成jar,然后部署到服务器中通过java -jar xxx.jar运行项目以后,项目中存在文件上传 ...
- java框架之SpringBoot(9)-数据访问及整合MyBatis
简介 对于数据访问层,无论是 SQL 还是 NOSQL,SpringBoot 默认采用整合 SpringData 的方式进行统一处理,添加了大量的自动配置,引入了各种 Template.Reposit ...
随机推荐
- 【转载】Spring学习(1)——快速入门--2019.05.19
原文地址:https://www.cnblogs.com/wmyskxz/p/8820371.html 认识 Spring 框架 Spring 框架是 Java 应用最广的框架,它的成功来源于理念 ...
- settings.py相关配置
INSTALLED_APPS #配置项目绑定的应用 TEMPLATES #配置项目使用的模板引擎 DATABASES #设定绑定的数据库 TIME_ZONE #设定时区,时区的设定可能 ...
- MySQL索引知识学习笔记
目录 一.索引的概念 二.索引分类 三.索引用法 四 .索引架构简介 五.索引适用的情况 六.索引不适用的情况 继我的上篇博客:Oracle索引知识学习笔记,再记录一篇MySQL的索引知识学习笔记,本 ...
- Python的定时器与线程池
定时器执行循环任务: 知识储备 Timer(interval, function, args=None, kwargs=None) interval ===> 时间间隔 单位为s functio ...
- Express中app.use()用法 详解
app.use(path,callback)中的callback既可以是router对象又可以是函数 app.get(path,callback)中的callback只能是函数 当一个路由有好多个子路 ...
- elasticsearch 索引的使用(配合haystack)
1,# 从仓库拉取镜像$ sudo docker image pull delron/elasticsearch-ik:2.4.6-1.02,下载elasticsearc-2.4.6目录拷贝到home ...
- python多进程multiprocessing Pool相关问题
python多进程想必大部分人都用到过,可以充分利用多核CPU让代码效率更高效. 我们看看multiprocessing.pool.Pool.map的官方用法 map(func, iterable[, ...
- 玩下PHP的分词,最近有这个需求
找了个地方 下载代码 我是在这里下载的 https://www.jb51.net/codes/65593.html 1 下载完毕后 打开是这样的文件 2 先把代码集成到thinkphp3.2.3里 ...
- Web前端——Html常用标签及属性
html 常用的标题等标签就不记录了,只记录一下比较少见的标签以及属性 表格 table td 单元格 tr 表的行 th 表头 td或th可以下面的两个属性达到跨行或跨列 表格跨行 rowspan ...
- ABAP 新语法记录(一)
原文链接:https://www.cnblogs.com/learnning/p/10647174.html 主要内容 内联声明 构造表达式 内表操作 Open SQL 其他 本文列出了ABAP新语法 ...