un7.7:如何在IDEA中实现图片上传功能并将图片展示出来?
在IDEA中如何实现图片的上传呢?接下来和我一起实现吧!
所需软件:
后端:IDEA
前端:HbuilderX
测试:火狐浏览器
一、在实体类中创建一个fileInfo类,定义一些属性,代码如下:
package com.xiaohui.cms.entity;public class FileInfo {private String fileName;private boolean isSecret;private String absolutPath;private String relativePath;public String getFileName() {return fileName;}public void setFileName(String fileName) {this.fileName = fileName;}public String getAbsolutPath() {return absolutPath;}public void setAbsolutPath(String absolutPath) {this.absolutPath = absolutPath;}public String getRelativePath() {return relativePath;}public void setRelativePath(String relativePath) {this.relativePath = relativePath;}public boolean isSecret() {return isSecret;}public void setSecret(boolean isSecret) {this.isSecret = isSecret;}public FileInfo() {}public FileInfo(String fileName, boolean isSecret, String absolutPath, String relativePath) {super();this.fileName = fileName;this.isSecret = isSecret;this.absolutPath = absolutPath;this.relativePath = relativePath;}@Overridepublic String toString() {return "FileInfo [fileName=" + fileName + ", isSecret=" + isSecret + ", absolutPath=" + absolutPath+ ", relativePath=" + relativePath + "]";}}
二、创建一个until工具包,然后创建一个JesyFileUploadUtil类,代码如下:
package com.xiaohui.cms.until;import java.io.IOException;
import java.util.Date;
import java.util.Random;import javax.net.ssl.SSLContext;import com.xiaohui.cms.entity.FileInfo;
import org.springframework.web.multipart.MultipartFile;import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties;/*** 跨服务器文件上传工具类* * @author qin**/
public class JesyFileUploadUtil {/*** 上传文件* * @param file --多媒体文件*/public static FileInfo uploadFile(MultipartFile file, String serverUrl) throws IOException {//把request请求转换成多媒体的请求对象
// MultipartHttpServletRequest mh = (MultipartHttpServletRequest) request;//根据文件名获取文件对象
// MultipartFile cm = mh.getFile(fileName);//获取文件的上传流byte[] fbytes = file.getBytes();//重新设置文件名String newFileName = "";newFileName += new Date().getTime()+""; //将当前时间获得的毫秒数拼接到新的文件名上//随机生成一个3位的随机数Random r = new Random();for(int i=0; i<3; i++) {newFileName += r.nextInt(10); //生成一个0-10之间的随机整数}//获取文件的扩展名String orginalFilename = file.getOriginalFilename();String suffix = orginalFilename.substring(orginalFilename.indexOf("."));//创建jesy服务器,进行跨服务器上传
// Client client = Client.create(getClientConfig());Client client = Client.create();//把文件关联到远程服务器//http://127.0.0.1:8080/ssm_image_server/upload/123131312321.jpgWebResource resource = client.resource(serverUrl+"/upload/"+newFileName+suffix);//上传resource.put(String.class, fbytes);//图片上传成功后要做的事儿//1、ajax回调函数做图片回显(需要图片的完整路径)//2、将图片的路径保存到数据库(需要图片的相对路径)String fullPath = serverUrl+"/upload/"+newFileName+suffix; //全路径String relativePath = "/upload/"+newFileName+suffix; //相对路径// //生成一个json响应给客户端
// String resultJson = "{\"fullPath\":\""+fullPath+"\", \"relativePath\":\""+relativePath+"\"}";
// return resultJson;return new FileInfo(newFileName+suffix, false, fullPath, relativePath);}}
三、创建一个filecontroller类,代码如下:
package com.xiaohui.cms.controller;import com.xiaohui.cms.entity.FileInfo;
import com.xiaohui.cms.until.JesyFileUploadUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;@RestController
@RequestMapping("/upload")
public class FileController {@PostMapping("/file")@ResponseBody@CrossOrigin(origins = "*")public String upload(MultipartFile file){String path = null;try {FileInfo fileInfo = JesyFileUploadUtil.uploadFile(file,"http://127.0.0.1:8060");path = fileInfo.getRelativePath();} catch (IOException e) {e.printStackTrace();}return path;}
}
四、修改yml配置文件,设置图片上传的大小,代码如下:
server:port: 8082
spring:datasource:url: jdbc:mysql://127.0.0.1:3306/t_cms?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8username: rootpassword: rootdriver-class-name: com.mysql.cj.jdbc.Driver #8.0??#driver-class-name: com.mysql.jdbc.Driver
# 是设置单个文件的大小,值=-1表示不限制大小servlet:multipart:max-file-size: 10MB # 单个文件的大小max-request-size: 100MB # 上传文件的总大小
五、打开HbuilderX文件,在需要添加的页面设置一个上传按钮,名字为“选择图片”,代码如下:
<view style="margin-bottom: 15rpx;">选择标题图(图片分辨率建议为:200px*200px)</view><button type="default" size="mini" @click="upload" :loading="loading">选择照片</button>
六、声明变量。
1、全局变量var _self
2、进度条和图片地址,如下:
imgPath: null,//图片的地址loading: false,
七、创建upload函数,实现上传,代码如下:
/*选择照片,上传照片*/upload(){_self = this;_self.loading = true;//选择图片,使用uni.chooseImgeuni.chooseImage({count: 1,sizeType:['original','compressed'],//指定上传图片是原图还是压缩,original原图,compressed压缩图sourceType:['album'],//从相册选择success: (res) => {const tempFilePath=res.tempFilePaths;//图片选择完成后,获取该图片的路径//上传图片,使用uni.uploadfileuni.uploadFile({url: "http://localhost:8082/upload/file",//找到上传文件的controllerfilePath: tempFilePath[0],//要上传的文件路径和上传的地基章图片name: 'file',//把文件放入file中success: (res) => {console.log(res);_self.loading = false;_self.imgPath = res.data;}});}}) }
八、测试。
1、上传前页面
2、上传成功页面
3、上传成功文件夹
我们可以看到上传成功后的页面图片只是一个路径,接下来就是需要将上传好的图片展示出来。
只需三步即可展示。
一、在article.vue文件中将logo这一行进行改动,代码如下:
<uni-td align="center"><image style="width: 80rpx;height: 80rpx;" :src="baseUrl+article.logo"></image></uni-td>
二、date中进行声明,地址写你服务器的端口号,如下:
baseUrl: "http://localhost:8060",
三、进行测试。
即可把上传的图片展示出来。
最后,附上HbuilderX中完整代码。
1、article.vue文件。
<template><view><menuDraw></menuDraw> <!--使用导入的组件--><uni-nav-bar title="文章管理" @clickLeft="doBack" leftText="返回" @clickRight="doSave" rightText="添加"></uni-nav-bar><uni-table :border="true" :stripe="true"><uni-tr><uni-th align="center">ID</uni-th><uni-th align="center">文章名称</uni-th><uni-th align="center">标题图片</uni-th><uni-th align="center">发布时间</uni-th><uni-th align="center">文章简述</uni-th></uni-tr><uni-tr v-for="article in articleList"><uni-td>{{article.id}}</uni-td><uni-td>{{article.name}}</uni-td><uni-td align="center"><image style="width: 80rpx;height: 80rpx;" :src="baseUrl+article.logo"></image></uni-td><uni-td>{{article.publishTime}}</uni-td><uni-td>{{article.descr}}</uni-td><uni-td align="center"><button @click="doUpdate(article.id)" type="primary" size="mini" style="margin-right: 10rpx;">修改</button><button @click="doDelete(article.id)" type="warn" size="mini">删除</button></uni-td></uni-tr></uni-table><!-- 分页器 --><uni-pagination:current="pageIndex":pageSize="pageSize":total="pageTotal"@change="pageChanged"/></view>
</template><script>import menuDraw from "../template/menu_draw.vue";//第一步:导入外部文件export default {//组件的声明components:{menuDraw//声明组件},data() {return {baseUrl: "http://localhost:8060",cid:null,//栏目idnice:"遇到你很高兴!",articleList: null,pageIndex:1,//页码pageSize:6,//每页展示数据的条数pageTotal:10 //数据总条数}},onLoad(options) {this.cid = options.cid;},/*当页面显示成功之后执行*/onShow() {this.requestUsers();/*定义请求用户列表的函数,通过http请求微服务用户列表*/},methods: {/*请求用户列表*/requestUsers(){/*uni_app的API发生http请求*/uni.request({url: 'http://localhost:8082/article/list', //仅为示例,并非真实接口地址。data:{cid:this.cid,pageIndex: this.pageIndex,pageSize: this.pageSize},success: (res) => {console.log(res.data);/*打印数据到控制台*/this.articleList = res.data.data;this.pageTotal = res.data.totle;}}); },//*当分页器被点击时触发*/pageChanged(e){//*当分页器被点击时触发console.log(e.current);//打印出当前点击的页码this.pageIndex = e.current;//给页码赋值this.requestUsers();},/*点击列表修改按钮时触发*/doUpdate(id){//console.log("用户修改:id="+id);uni.redirectTo({url:"./article_update?id="+id,})},/*点击分配权限按钮时触发*/doResource(id){uni.navigateTo({url: "../articleres/articleres?id="+id})},/*点击列表删除按钮时触发*/doDelete(id){//console.log("用户删除:id="+id);uni.request({url: "http://localhost:8082/article/delete?id="+id,success: (res) => {if(res.data.code == 200){//删除成功this.articleList = res.data.data;}}})},doBack(){uni.navigateBack();},doSave(){uni.redirectTo({url: "article_add?cid="+this.cid})}}}
</script><style></style>
2、article_add.vue文件。
<template><view><menuDraw></menuDraw><view style="width: 350rpx; margin-top:80rpx; margin-left:auto;margin-right: auto;"><uni-forms :modelValue="FormData"><uni-forms-item label="文章名称" name="name"><uni-easyinput type="text" v-model="FormData.name" placeholder="请输入文章名称"></uni-easyinput></uni-forms-item><uni-forms-item label="文章简述" name="descr"><uni-easyinput type="text" v-model="FormData.descr" placeholder="请输入文章简述"></uni-easyinput></uni-forms-item><view style="margin-bottom: 15rpx;">选择标题图(图片分辨率建议为:200px*200px)</view><button type="default" size="mini" @click="upload" :loading="loading">选择照片</button><button type="primary" @click="doSave">确认添加</button></uni-forms></view><!--弹出警告对话框--><uni-popup ref="popup" type="dialog"><uni-popup-dialog mode="base" title="通知" :content="msg" :beforeClose="true" @close="close" @confirm="confirm"></uni-popup-dialog></uni-popup></view>
</template><script>import menuDraw from "../template/menu_draw.vue";var _self;export default {components:{menuDraw//声明组件},data() {return {imgPath: null,//图片的地址loading: false,FormData:{cid:null,//栏目idname:null,//名称descr:null//文章简述},msg:null //警告对话框提示的信息}},onLoad(options) {this.cid = options.cid;},methods: {/*添加用户*/doSave(){//console.log(this.FormData.phone)//console.log(this.FormData.articlename)uni.request({url: "http://localhost:8082/article/add",data:{name:this.FormData.name,descr:this.FormData.descr,cid:this.cid,logo: this.imgPath},method:"GET",success: (res) => {if(res.data.code==200){//保存成功uni.redirectTo({url:"article?cid="+this.cid})}else{//保存失败this.msg=res.data.msg;this.open();}}})},//点击对话框确认按钮执行的操作confirm(){this.$refs.popup.close();},/*点击对话框关闭按钮执行的操作*/close() {this.$refs.popup.close();},//弹出警告对话框open() {this.$refs.popup.open();},/*选择照片,上传照片*/upload(){_self = this;_self.loading = true;//选择图片,使用uni.chooseImgeuni.chooseImage({count: 1,sizeType:['original','compressed'],//指定上传图片是原图还是压缩,original原图,compressed压缩图sourceType:['album'],//从相册选择success: (res) => {const tempFilePath=res.tempFilePaths;//图片选择完成后,获取该图片的路径//上传图片,使用uni.uploadfileuni.uploadFile({url: "http://localhost:8082/upload/file",//找到上传文件的controllerfilePath: tempFilePath[0],//要上传的文件路径和上传的地基章图片name: 'file',//把文件放入file中success: (res) => {console.log(res);_self.loading = false;_self.imgPath = res.data;}});}}) }}}
</script><style></style>
3、article_update.vue文件。
<template><view><menuDraw></menuDraw><view style="width: 350rpx; margin-top:80rpx; margin-left:auto;margin-right: auto;"><uni-forms :modelValue="FormData"><uni-forms-item label="文章名称" name="name"><uni-easyinput type="text" v-model="FormData.name" placeholder="请输入文章名称"></uni-easyinput></uni-forms-item><uni-forms-item label="文章简述" name="descr"><uni-easyinput type="text" v-model="FormData.descr" placeholder="请输入文章简述"></uni-easyinput></uni-forms-item><uni-forms-item label="栏目id" name="cid"><uni-easyinput type="text" v-model="FormData.cid" placeholder="请输入栏目id"></uni-easyinput></uni-forms-item><button type="primary" size="mini" @click="doUpdate">修改</button></uni-forms></view><!--弹出警告对话框--><uni-popup ref="popup" type="dialog"><uni-popup-dialog mode="base" title="通知" :content="msg" :beforeClose="true" @close="close" @confirm="confirm"></uni-popup-dialog></uni-popup></view>
</template><script>import menuDraw from "../template/menu_draw.vue";export default {components:{menuDraw//声明组件},/*当页面加载成功之后触发,用于接收页面跳转及传参*/onLoad(options) {this.id=options.id;console.log("接收页面传参:"+this.id);},/*当页面渲染成功之后执行*/onShow() {this.requestUserInfo();/*定义请求用户列表的函数,通过http请求微服务用户列表*/},data() {return {id:null, //页面传参的用户idFormData:{name:null,//文章名称descr:null,//文章简述cid:null//栏目id},msg:null //警告对话框提示的信息}},methods: {/*修改文章*/doUpdate(){uni.request({url: "http://localhost:8082/article/update",data:{name:this.FormData.name,descr:this.FormData.descr,cid:this.FormData.cid,id:this.id},method:"GET",success: (res) => {if(res.data.code==200){//保存成功uni.navigateBack()}else{//保存失败this.msg=res.data.msg;this.open();}}});},//点击对话框确认按钮执行的操作confirm(){this.$refs.popup.close();},/*点击对话框关闭按钮执行的操作*/close() {this.$refs.popup.close();},//弹出警告对话框open() {this.$refs.popup.open();},/*获取文章信息*/requestUserInfo(){uni.request({url:"http://localhost:8082/article/info?id="+this.id,success:(res) =>{console.log(res.data)this.FormData=res.data.data;}})}}}
</script><style></style>
如此,我们就可以实现在前后端分离的情况下进行图片上传并实现图片展示了,快行动起来吧。
un7.7:如何在IDEA中实现图片上传功能并将图片展示出来?相关推荐
- 如何用java创建超链接_Java如何在PPT中的幻灯片上创建超链接?
在Java编程中,如何在PPT中的幻灯片上创建超链接? 注意:需要访问网址:http://poi.apache.org/download.html , 下载一个Apache POI软件包.这里下载最新 ...
- [ASP.NET2.0] asp.net在ie7中使用FileUpload上传前预览图片 [ZT]
asp.net在ie7中使用FileUpload上传前预览图片 因为安全性问题,IE7禁用了image控件引用本地图片,为了这个问题郁闷了好几天,终于找到了解决方案,好东西要与大家分享,代码如下: 此 ...
- 如何在Linux中使用sFTP上传或下载文件与文件夹
如何在Linux中使用sFTP上传或下载文件与文件夹 sFTP(安全文件传输程序)是一种安全的交互式文件传输程序,其工作方式与 FTP(文件传输协议)类似. 然而,sFTP 比 FTP 更安全;它通过 ...
- Web开发中图片上传功能总结
图片上传功能总结 1.添加文件上传所需jar包(commons-io-1.4.jar和commons-fileupload-1.1.1.jar) 2.在form表单上添加自带属性 enctyp ...
- android 调取数字键盘,如何在android中的EditText上显示数字键盘?
如何在android中的EditText上显示数字键盘? 我只是想在某个EditText具有焦点时立即切换到数字键盘模式. 13个解决方案 239 votes 您可以为EditText配置EditTe ...
- php layui ajax多图上传,Laravel+Layer实现图片上传功能(整理篇)
♩ 背景 昨天在自己的 Laravel5.5 框架项目中,希望集成 Layer 的图片上传功能 但是在 ajax(POST) 提交请求时,一直显示 500 报错 ♪ 分析 ⒈ 问题所在 最后将核心代码 ...
- 百度编辑器图片上传功能解疑
最头疼的上传图片问题 版本选择和自定义配置 项目中使用了百度编辑器ueditor,这里是官网链接,效果还算不错,使用中的一些经验,分享在这里. 我使用的环境是.NET MVC3 最头疼的上传图片问题 ...
- 如何去掉图片上的水印而不损图片
平时不管是发朋友圈还是发布自媒体,都需要图片的结合,而很多图片我们都是来自百度,但是有一点不好的就是很多图片中都会有水印的存在,给我们的视觉效果会有一定的影响,所以就想着将图片中的水印去掉,平时大多数 ...
- 人人网的相册里图片上传功能是怎样实现的
大侠们,给我讲解下类似于人人网的相册里,图片上传功能是怎么实现的,它可以批量上传.我的想法是实现一个批量上传图片的功能,1.可以让用户同时选择多个图片上传.2.上传后会显示出来,并且可以单独对某张图进 ...
最新文章
- R语言使用ggplot2包geom_jitter()函数绘制分组(strip plot,一维散点图)带状图(水平带状图、垂直带状图、抖动程度配置)实战
- C#进行MapX二次开发之控件基本操作
- 高并发之CAS机制和ABA问题
- 计算机专业大二分方向,该选择人工智能还是网络安全
- php tcp和udp的区别,HTTPS 和 HTTP、UDP 和 TCP 的区别
- SQL模糊查询语句和Escape转义字符
- Jquery消息提示插件toastr使用详解
- 基于matlab移位寄存器,基于Matlab产生m序列(DOC X页).doc
- 计算机中那些事儿(四):我眼中的虚拟技术
- 网络传输---HttpURLConnection
- Atitit 知识点 文章 框架 结构 大纲 attilax 总结 艾提拉总结 技术掌握文档总结的 v5 s420.docx 1.1. Preface前言 序言	1 2. 技术流程了解》》选型(标准
- SENT:Sentence-level Distant Relation Extraction via Negtive Training-ACL2021
- am355x armlinux 移植openssh
- python身份证号码共18位_用Python写一个身份证号码校验工具
- 如何修改 / 校正Linux系统时间
- Wireshark 网卡出错 The capture session could not be initiated on interface ‘en0‘
- UVA10158 - War(并查集)
- 评价页面html,利用html与css制作5星好评页面
- D:\anaconda3\envs\py2\python.exe: can‘t open file ‘create‘: [Errno 2] No such file or directory
- Android 6.0 更新包与已安装应用的签名不一致