本人是刚毕业的新手,最近公司的一个项目,前后端分离,前端Vue,后端使用spring boot。其中有一个需求是需要做前端上传的图片需要压缩才能上传。为此在网上查找资料,并做了简单的实现。

那么一步来

一。前端

1.先写界面,考虑到时间问题,就先写个简单的页面,创建个Imagepress.vue

 <template>
<div>
<input id="inputele" type="file" accept="image/*" @change="readImg">
<canvas id="canvasImg" ></canvas>
</div>
</template>

2.当用户点击,上传图片时,触发change事件,调用readImg方法。readImg方法如下:

 readImg: function(e){
let that=this
console.log('123')
let file = e.target.files[0]
let reader = new FileReader()
let img = new Image()
reader.readAsDataURL(file)
//console.log(file) let canvas = document.getElementById('canvasImg');
let context = canvas.getContext('2d');
reader.onload = function(e) {// 文件base64,可以看看结果
img.src = e.target.result;
//console.log('文件base64,可以看看结果'+img.src);
}
img.onload=function(){
let w=this.width,h=this.height
let width=w,height=h
let size=400
if (w>=h&&w>size) {//宽>高
width=size
height=size/w*h
} else if (w<h&&h>size) {
height=size
width=size/h*w
}
let canvas = document.getElementById('canvasImg');
let context = canvas.getContext('2d'); //计算画布的大小
canvas.width=width
canvas.height=height
context.clearRect(0,0,width,height)
//img重新画到特定大小的画布上
context.drawImage(img,0,0,width,height)
//画完之后的互补就是压缩之后的图片canvas
//缩略图canvas转为二进制的数据用于上次
// canvas.toBlob(function(blob){
// console.log('哈哈,开始上传压缩的图片了')
// console.log(blob)
// that.$http.post('http://127.0.0.1:8088/index',blob)
// })
let newData=canvas.toDataURL("image/png",0.3)
console.log(typeof(newData))
let files=new Array()
files.push(newData)
that.$http.post('http://localhost:8088/index',files)
}
}

a.首先是fileReader 读取上传上来的图片file,

b.计算canvas画布的大小,将读取的img重新画到特定到校的画布上

c.最后调用cavas.toDataURL("image/png",0.3)进行压缩,该方法有2个参数,第一个是指定图片的格式,第二个参数是指定压缩图片的质量,取值在0-1之间,返回值是一个 data URI 的DOMString。

页面效果

按F12打开开发者工具

可以看到已经向后台发起请求了。

二。后端

  

后端我是使用的是spring boot,至于spring boot的细节在这里就不赘述了。

在前端我们请求的地址是http://localhost:8088/index

所以后台代码

@RequestMapping(value="/index",method=RequestMethod.POST)

public String uploadimg(@RequestBody String[] files) throws Exception{

}

具体代码如下

 @RequestMapping(value="/index",method=RequestMethod.POST)
public String uploadimg(@RequestBody String[] files) throws Exception{ if(files==null||files.length==0)
return null;
String data="";
String dataprefix=""; for(String file:files){
String[] str=file.split("base64,");
if(str==null||str.length!=2)
return null;
dataprefix=str[0];
data=str[1];
String suffix = "";
if("data:image/jpeg;".equalsIgnoreCase(dataprefix)){//data:image/jpeg;base64,base64编码的jpeg图片数据
suffix = ".jpg";
} else if("data:image/x-icon;".equalsIgnoreCase(dataprefix)){//data:image/x-icon;base64,base64编码的icon图片数据
suffix = ".ico";
} else if("data:image/gif;".equalsIgnoreCase(dataprefix)){//data:image/gif;base64,base64编码的gif图片数据
suffix = ".gif";
} else if("data:image/png;".equalsIgnoreCase(dataprefix)){//data:image/png;base64,base64编码的png图片数据
suffix = ".png";
}else{
throw new Exception("上传图片格式不合法");
} //因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
byte[] bs = Base64Utils.decodeFromString(data);
//FileUtils.writeByteArrayToFile(new File(savepath+System.currentTimeMillis()+suffix), bs);
FileOutputStream out=new FileOutputStream(new File(savepath+System.currentTimeMillis()+suffix));
out.write(bs);
out.flush();
out.close();
}
return "开始上传图片";
}

具体图片的保存地址我配置在了application.yml中,具体如下

server:
port: 8088

savepath: E:/images/

发现压缩的图片也保存好了,查看图片的大小,发现图片确实变小了。

现在基本完成图片的压缩上传。在手机端也是没有问题的。

作为刚毕业没毕业多久的人,肯定还有不足,若有不足请各位大佬多多提醒。这是第一篇博客,也请各位多多留言。

基于前台vue,后台是spring boot的压缩图片上传的更多相关文章

  1. Vue页面内公共的多类型附件图片上传区域并适用折叠面板

    在前端项目中,附件上传是很常用的功能,几乎所有的app相关项目中都会使用到,一般在选择使用某个前端UI框架时,可以查找其内封装好的图片上传组件,但某些情况下可能并不适用于自身的项目需求,本文中实现的附 ...

  2. SpringMVC+Spring+MyBatis 整合与图片上传简单示例

    一.思路: (一) Dao层: 1. SqlMapConfig.xml,空文件即可.需要文件头.2. applicationContext_dao.xml. a) 数据库连接池b) SqlSessio ...

  3. Spring Boot 嵌入式 Tomcat 文件上传、url 映射虚拟路径

    1.Java web 应用开发完成后如果是导入外置的 Tomcat 的 webapps 目录的话,那么上传的文件可以直接的放在应用的 web 目录下去就好了,浏览器可以很方便的进行访问. 2.Spri ...

  4. spring boot实现切割分片上传

    文件上传是web开发中经常会遇到的 springboot的默认配置为10MB,大于10M的是传不上服务器的,需要修改默认配置 但是如果修改支持大文件又会增加服务器的负担. 当文件大于一定程度时,不仅服 ...

  5. 解决使用Spring Boot、Multipartfile实现上传提示无法找到文件的问题

    前言 SpringBoot使用MultiPartFile接收来自表单的file文件,然后进行服务器的上传是一个项目最基本的需求,我以前的项目都是基于SpringMVC框架搭建的,所以在使用Spring ...

  6. Spring Boot + thymeleaf 实现文件上传下载

    参考博客:https://juejin.im/post/5a326dcaf265da431048685e 技术选型:spring boot 2.1.1+thymeleaf+maven 码云地址:htt ...

  7. Spring Boot入门——多文件上传大小超限问题解决

    多文件上传中遇到上传文件大小的问题 org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededExcepti ...

  8. spring boot 长时间运行上传报临时目录找不到

    The temporary upload location [/tmp/tomcat-docbase.3752410576653354473.8899/work/Tomcat/localhost/RO ...

  9. MUI + Spring MVC 实现多图片上传

    后台代码,主要是SpringMVC 接收多文件上传,不是用的MutilFiles 方式,主要是因为MUI 5+ 不支持文件上传的Key是同一个名字 private String saveFile(Mu ...

随机推荐

  1. 基于C++的牛顿切线法演示

    牛顿切线法 中心思想: 利用目标函数二阶泰勒多项式的最优解作为函数的近似最优解.如果新的近似最优解满足计算精度,则终止计算,否则将函数在新点展开成二阶泰勒多项式,用新的泰勒多项式的最优解作为函数的近似 ...

  2. bzoj 4589 FWT

    #include<bits/stdc++.h> #define ll long long using namespace std; ; ; ; ; <<],b[<< ...

  3. redis(4.0.11)编译安装

    一: redis数据库安装 系统环境:linux系统(centos/redhat):Red Hat Enterprise Linux Server release 6.8 (Santiago) red ...

  4. No matching authentication protocol

    java 连接oracle数据库: 之前连接公司的oracle数据库没有问题,但客户提供的是oracle12C版本的,连接就报 :No matching authentication protocol ...

  5. java 大数运算[转]

    用JAVA 实现算术表达式(1234324234324 + 8938459043545)/5 + 343434343432.59845 因为JAVA语言中的long 定义的变量值的最大数受到限制,例如 ...

  6. 代理IP

    代理IP 一.获取代理IP 二.使用代理IP 1.requests 2. selenium 2.1 selenium+chrome 2.2 selenium+Firefox 2.3 selenium+ ...

  7. 解决spring-boot配置文件使用加密方式保存敏感数据启动报错No decryption for FailsafeTextEncryptor. Did you configure the keystore correctly

    spring-boot配置文件使用加密方式保存敏感数据 application.yml spring: datasource: username: dbuser password: '{cipher} ...

  8. [UE4]Spline

    Spline和Spline Mesh的区别: 1.Spline Mesh是有实体表现的,Spline Mesh可以拉伸弯曲实体模型,Spline Mesh是具象. 2.Spline 只有曲线,没有实体 ...

  9. Tree Traversals Again

    An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example ...

  10. yum搭建 Lamp环境

    yum搭建Lamp yum install -y httpd yum install -y nano rpm 安装 Php7 相应的 yum源 rpm -Uvh https://dl.fedorapr ...