java-springboot实现图片的上传

我们在resources目录下创建image目录来存放上传的图片 

 

service层懒的写,就都写controller层了。


@RestController
@RequestMapping("/upload")
public class upload {@PostMapping("/pic")public String upLoad(@RequestParam("multipartFile")MultipartFile multipartFile) {//判断图片是否存在if (multipartFile.isEmpty()) {return null;}//图片的新名字,使用uuid为了图片名字的唯一性,防止重名String name = UUID.randomUUID().toString().replace("-","");/** 获取上传图片的后缀* multipartFile.getOriginalFilename()获取图片名字* 例如:图片名字是picture.png,最后type会等于.png* substring和lastIndexOf都是String的方法,不会自己搜*/String type = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf('.'));//保存图片的路径,我们存放在resources下static下的imageString value = "src/main/resources/static/image/";//创建文件File file = new File(value+name+type);try {//transferTo 图片复制multipartFile.transferTo(file);} catch (IOException e) {throw new RuntimeException(e);}return file.getAbsolutePath();}
}

我们使用postman传照片。

结果报错了,明显我们要保存的路径是不对的,为什么,因为 multipartFile 要的是绝对路径,不是相对路径,如果是相对路径的话,他不会在你相对路径前面添加你项目的路径,而是tomcat的路径,因此我们修改一下。 

修改后:

@RestController
@RequestMapping("/upload")
public class upload {@PostMapping("/pic")public String upLoad(@RequestParam("multipartFile")MultipartFile multipartFile) {//判断图片是否存在if (multipartFile.isEmpty()) {return null;}//图片的新名字,使用uuid为了图片名字的唯一性,防止重名String name = UUID.randomUUID().toString().replace("-","");/** 获取上传图片的后缀* multipartFile.getOriginalFilename()获取图片名字,例如:picture.png* substring和lastIndexOf都是String的方法,不会自己搜*/String type = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf('.'));//保存图片的路径,我们存放在resources下static下的image//修改后的代码String value = "D:/code/picture/src/main/resources/static/image/";//创建文件File file = new File(value+name+type);try {//transferTo 图片复制multipartFile.transferTo(file);} catch (IOException e) {throw new RuntimeException(e);}return file.getAbsolutePath();}
}

我们再使用postman上传 

结果对了:我们的目录出现了上传的图片



一般照片的访问路径是要保存到数据库,然后前端根据路径找到照片的。

@RestController
@RequestMapping("/upload")
public class upload {@PostMapping("/pic")public String upLoad(@RequestParam("multipartFile")MultipartFile multipartFile) {//判断图片是否存在if (multipartFile.isEmpty()) {return null;}//图片的新名字,使用uuid为了图片名字的唯一性,防止重名String name = UUID.randomUUID().toString().replace("-","");/** 获取上传图片的后缀* multipartFile.getOriginalFilename()获取图片名字,例如:picture.png* substring和lastIndexOf都是String的方法,不会自己搜*/String type = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf('.'));//保存图片的路径,我们存放在resources下static下的imageString value = "D:/code/picture/src/main/resources/static/image/";//创建文件File file = new File(value+name+type);try {//transferTo 图片复制multipartFile.transferTo(file);} catch (IOException e) {throw new RuntimeException(e);}//在数据库保存照片的访问路径,数据库懒得建,就没写。// 打印程序的 IP 地址、端口号和照片路径//这里获取ip地址和端口号有高级写法,自己搜。但是我这么写也没毛病。String photoUrl = "http://" + "127.0.0.1" + ":" + "8080" + "/image/" + file.getName();System.out.println(photoUrl);return file.getAbsolutePath();}
}

 我们浏览器是能访问到的。


 如果你的程序要部署到云服务器上,那绝对路径和照片的url是要更改的

        // 使用 System 类的 getProperty() 方法获取用户的当前工作目录// 如果路径是这个D:/code/picture/src/main/resources/static/image/// userDir 会是 D:\code\pictureString userDir = System.getProperty("user.dir");//保存图片的路径,我们存放在resources下static下的imageString value = userDir + "\\src\\main\\resources\\static\\image\\";
      //这要写你的云服务器的ipString ip = "127.0.0.1";//你程序的端口号String port = "8080";String photoUrl = "http://" + ip + ":" + port + "/image/" + file.getName();//保存到你的数据库

完整代码:

@RestController
@RequestMapping("/upload")
public class upload {@PostMapping("/pic")public String upLoad(@RequestParam("multipartFile")MultipartFile multipartFile) {//判断图片是否存在if (multipartFile.isEmpty()) {return null;}//图片的新名字,使用uuid为了图片名字的唯一性,防止重名String name = UUID.randomUUID().toString().replace("-","");/** 获取上传图片的后缀* multipartFile.getOriginalFilename()获取图片名字,例如:picture.png* substring和lastIndexOf都是String的方法,不会自己搜*/String type = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf('.'));// 使用 System 类的 getProperty() 方法获取用户的当前工作目录// 如果路径是这个D:/code/picture/src/main/resources/static/image/// userDir 会是 D:\code\pictureString userDir = System.getProperty("user.dir");//保存图片的路径,我们存放在resources下static下的imageString value = userDir + "\\src\\main\\resources\\static\\image\\";//创建文件File file = new File(value+name+type);try {//transferTo 图片复制multipartFile.transferTo(file);} catch (IOException e) {throw new RuntimeException(e);}//在数据库保存照片的访问路径,数据库懒得建,就没写。// 打印程序的 IP 地址、端口号和照片路径//这里获取ip地址和端口号有高级写法,自己搜。但是我这么写也没毛病。//这要写你的云服务器的ipString ip = "127.0.0.1";//你程序的端口号String port = "8080";String photoUrl = "http://" + ip + ":" + port + "/image/" + file.getName();System.out.println(photoUrl);return file.getAbsolutePath();}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/772683.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

PTA金字塔游戏

幼儿园里真热闹,老师带着孩子们做一个名叫金字塔的游戏,游戏规则如下: 首先,老师把孩子们按身高从高到矮排列,选出最高的做队长,当金字塔的塔顶,之后在其余小朋友里选出两个最高的,…

12个好玩又实用的Python迭代器和生成器实例

大家好!今天我们要来一场编程奇趣之旅,一起揭秘那些既让代码变得更简洁高效,又能带你领略Python魅力的12个迭代器和生成器实例。别担心,我会用轻松易懂的语言帮你掌握这些小技巧,准备好你的笔记本,咱们这就…

Vue3 + Vite + TS + Element-Plus + Pinia项目整理(2)

1、清空App.vue文件内容&#xff0c;替换成下面 <template><router-view></router-view> </template> 2、清空style.css文件内容&#xff0c;替换成下面内容 *{margin: 0;padding: 0;list-style: none;text-decoration: none;outline: none;box-siz…

MySQL 练习三

select sname,sex,class from student;select distinct depart from teacher;select * from student;select * from score where degree between 60 and 80;select * from score where degree in(85,86,88);select * from student where class’95031’ or sex’女’;select * …

RAG( Retrieval Augmented Generation)简单实现

RAG基础知识: https://python.langchain.com/docs/use_cases/question_answering/ 本文主要讲解通过Langchain 和Ollama这2个工具实现RAG。 Langchain: https://python.langchain.com/docs/get_started/introduction Ollama: https://ollama.com/ 先简单理清一下RAG, Langc…

transductive transfer learning

如图所示&#xff0c;传统的机器学习方法尝试去学习每一种任务&#xff0c;而迁移学习则根据已经学习处理过的任务推广到有较少训练数据的新任务上。在传统的机器学习中&#xff0c; transductive learning指所有测试数据在训练时被要求看到的情况&#xff0c;并且对于新的数据…

谈谈计算机科学与技术这门专业

原文地址&#xff1a;谈谈计算机科学与技术这门专业 - Pleasure的博客 下面是正文内容&#xff1a; 前言 这是一篇个人性质的笔记。 专业代码080901 或许也可以理解为计算机科学与技术专业大致都要经历的学习路线&#xff08;主要还是根据本校&#xff09;。 正文 主要专业课程…

Redis中的事件(二)

文件事件 文件事件的处理器 Redis为文件事件编写了多个处理器&#xff0c;这些事件处理器分别用于实现不同的网络通信需求&#xff0c;比如说: 1.为了对连接服务器的各个客户端进行应答&#xff0c;服务器要为监听套接字关联连接应答处理器2.为了接收客户端传来的命令请求&a…

数据结构与算法分析引论1

1.解决问题的算法有很多&#xff0c;但是在输入不同的情况下&#xff0c;不同算法之间的差异也很大&#xff0c;我们总是追求一个更快、更有效的方法。比如说普通的依次查找和二分查找&#xff0c;两者的差异就很大。我们使用大O表示法来表示算法的速度。依次查找就是O(n)&…

Fiddler抓包工具之Fiddler界面主菜单功能介绍

Fiddler界面主菜单功能介绍 File菜单 File菜单中的命令主要支持完成通过Fiddler来启动和停止web流量的捕获&#xff08;capture&#xff09;,也可以加载或存储捕获的流量 &#xff08;1&#xff09;Capture Traffic&#xff1a;默认勾选&#xff0c;勾选此项才可抓包&#xff…

USB HOST移植

一、USB简介 USB有USB1.0/1.1/2.0/3.0多个版本&#xff0c;标准USB由4根线组成,VCC&#xff0c;GND&#xff0c;D&#xff0c;D-&#xff0c;其中D和D-是数据线&#xff0c;采用差分传输。 在USB主机上,D-和D都是接了15K的电阻到地,所以在没有设备接入的时候,D、D-均是低电平。…

KCP部署NodeJS

一、windows下环境 安装python3.10.10 注意勾选add path&#xff0c;添加环境变量 安装windows-build-tools 以下代码&#xff0c;会在当前路径下载一个windows-build-tools npm install --production windows-build-tools tools 需要勾选C开发工具 二、linux下环境 腾讯…

Scala环境搭建

目录 前言 Scala的概述 Scala环境的搭建 一、配置Windows的JAVA环境 二、配置Windows的Scala环境 编写一个Scala程序 前言 学习Scala最好先掌握Java基础及高级部分知识&#xff0c;文章正文中会提到Scala与Java的联系&#xff0c;简单来讲Scala好比是Java的加强版&#x…

【Java多线程(2)】Thread常见方法和线程状态

目录 一、Thread类及常见方法 1. join() 等待一个线程 2. currentThread() 获取当前线程引用 3. sleep() 休眠当前线程 二、线程的状态 1. 线程的所有状态 2. 状态转移 一、Thread类及常见方法 接上文&#xff1a;多线程&#xff08;1&#xff09;http://t.csdnimg.cn/…

git-怎样把连续的多个commit合并成一个?

Git怎样把连续的多个commit合并成一个&#xff1f; Git怎样把连续的多个commit合并成一个&#xff1f; 参考URL: https://www.jianshu.com/p/5b4054b5b29e 查看git日志 git log --graph比如下图的commit 历史&#xff0c;想要把bai “Second change” 和 “Third change” 这…

【Linux系统zabbix安装部署】

1、安装lamp环境 [rootlocalhost software]# yum -y install mariadb mariadb-server httpd php php-mysql [rootlocalhost software]# systemctl enable httpd [rootlocalhost software]# systemctl restart htpd [rootlocalhost software]# systemctl restart httpd [rootloc…

cinder学习小结

1 官方文档 翻译官方文档学习 链接Cinder Administration — cinder 22.1.0.dev97 documentation (openstack.org) 1.1 镜像压缩加速 在cinder.conf配allow_compression_on_image_upload True可打开开关 compression_format xxx可设置镜像压缩格式&#xff0c;可为gzip 1.2 …

手撕算法-数组中的第K个最大元素

描述 分析 使用小根堆&#xff0c;堆元素控制在k个&#xff0c;遍历数组构建堆&#xff0c;最后堆顶就是第K个最大的元素。 代码 class Solution {public int findKthLargest(int[] nums, int k) {// 小根堆PriorityQueue<Integer> queue new PriorityQueue<>…

【python从入门到精通】-- 第二战:注释和有关量的解释

&#x1f308; 个人主页&#xff1a;白子寰 &#x1f525; 分类专栏&#xff1a;python从入门到精通&#xff0c;魔法指针&#xff0c;进阶C&#xff0c;C语言&#xff0c;C语言题集&#xff0c;C语言实现游戏&#x1f448; 希望得到您的订阅和支持~ &#x1f4a1; 坚持创作博文…

鸿蒙 HarmonyOS应用开发之API:Context

Context 是应用中对象的上下文&#xff0c;其提供了应用的一些基础信息&#xff0c;例如resourceManager&#xff08;资源管理&#xff09;、applicationInfo&#xff08;当前应用信息&#xff09;、dir&#xff08;应用文件路径&#xff09;、area&#xff08;文件分区&#x…