Springboot上传图片并访问

步骤

  1. 配置绝对路径,并将这个绝对路径添加到springboot静态资源目录中。

  2. 文件上传使用绝对路径保存。返回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上传图片并访问的更多相关文章

  1. 六、SpringBoot与数据访问

    六.SpringBoot与数据访问 1.JDBC spring: datasource: username: root password: 123456 url: jdbc:mysql://192.1 ...

  2. (转)SpringBoot非官方教程 | 第三篇:SpringBoot用JdbcTemplates访问Mysql

    本文介绍springboot通过jdbc访问关系型MySQL,通过spring的JdbcTemplate去访问. 准备工作 jdk 1.8 maven 3.0 idea mysql 初始化mysql: ...

  3. SpringBoot非官方教程 | 第三篇:SpringBoot用JdbcTemplates访问Mysql

    转载请标明出处: 原文首发于https://www.fangzhipeng.com/springboot/2017/07/11/springboot3-JdbcTemplates-Mysql/ 本文出 ...

  4. 第三篇:SpringBoot用JdbcTemplates访问Mysql

    本文介绍springboot通过jdbc访问关系型mysql,通过spring的JdbcTemplate去访问. 准备工作 jdk 1.8 maven 3.0 idea mysql 初始化mysql: ...

  5. https://segmentfault.com/a/1190000012844836---------关于SpringBoot上传图片的几种方式

    关于SpringBoot上传图片的几种方式 https://segmentfault.com/a/1190000012844836

  6. springboot 静态资源访问,和文件上传 ,以及路径问题

    springboot 静态资源访问: 这是springboot 默认的静态资源访问路径  访问顺序依次从前到后(http://localhost:8080/bb.jpg) spring.resourc ...

  7. SpringBoot之数据访问和事务-专题三

    SpringBoot之数据访问和事务-专题三 四.数据访问 4.1.springboot整合使用JdbcTemplate 4.1.1 pom文件引入 <parent> <groupI ...

  8. 解决springboot项目打成jar包部署到linux服务器后上传图片无法访问的问题

    前言:目前大三,自己也在学习和摸索的阶段.在和学校的同学一起做前后端分离项目的时候,我们发现将后端打包成jar,然后部署到服务器中通过java -jar xxx.jar运行项目以后,项目中存在文件上传 ...

  9. java框架之SpringBoot(9)-数据访问及整合MyBatis

    简介 对于数据访问层,无论是 SQL 还是 NOSQL,SpringBoot 默认采用整合 SpringData 的方式进行统一处理,添加了大量的自动配置,引入了各种 Template.Reposit ...

随机推荐

  1. go语言设计模式之Concurrency barrier

    barrier.go package barrier import ( "fmt" "io/ioutil" "net/http" " ...

  2. AtCoder Regular Contest 103

    传送门 C - /\/\/\/ 题意: 给出一个序列\(\{a_i\}\),先要求其满足以下条件: \(a_i=a_{i+2}\) 共有两个不同的数 你现在可以修改任意个数,现问最少修改个数为多少. ...

  3. Java成员变量和局部变量区别

    成员变量和局部变量区别 变量根据定义位置的不同,我们给变量起了不同的名字.如下图所示: 区别 在类中的位置不同  (重点) 成员变量:类中,方法外 局部变量:方法中或者方法声明上(形式参数) 作用范围 ...

  4. 黄聪:不使用 webpack,vuejs 异步加载模板

    webpack 打包不会玩,整了这么个小玩具 一段 vue 绑定代码,关键点在 gmallComponent 1.异步加载外部 vue 文件(非 .vue) 2.按一定规则拆分 template.sc ...

  5. [debug]ubuntu共享文件夹所在目录

    使用Vmware虚拟机,Vmware Tools工具的复制粘贴一直无效,之后采用共享文件夹. 其默认的是在 \mnt\hgfs 下,在Vmware的设置中建立好文件夹,将文件传入进去,之后就可以去 \ ...

  6. 关于python的十一道练习

    关于python的十一道练习 1.编写程序,输入一个自然数字符串,然后输出各位数字之和.例如,输入字符串1234,输出10. def sums1(): #第一题 strs=input('请输入一个自然 ...

  7. 配置文件_自定义section标签获取数据

    前言:为了节约时间,先只粘贴关键代码: 1-添加section标签,name为自定义标签名称,type为:命名空间+类型,程序集名称 <section name="watchModel ...

  8. 零零总总遇到过的CSS 样式

    1:添加弹出框阴影 2:禁止文本域缩放 3:直接使用CSS 完成文本内容大小写(针对英文) 4: 文本框中的占位符 5:让table每列一样高 6:不使用js 让内容换行 word-break 7:曾 ...

  9. .net WebApi 批量文件进行压缩zip以二进制流传输至前端(Vue)下载

    前言:最近接了个项目,需要进行将服务端生成的文件进行打包压缩供前端下载,百度查了下资料,决定采用SharpZipLib C#开园的压缩解压库进行服务器文件压缩,在实现过程,郁闷的是前端接收下载下来的压 ...

  10. 移动端适配方案(rem+flex)

    为什么用rem不用px? 主流:各大网站的移动版绝大多数都是用的rem.   移动端屏幕分辨率差别太大:最低适配的iPhone6,分辨率仅为750*1334.而现在市面上大多数手机,都达到了1080* ...