赞
踩
(1)uniapp图片上传存在图片太大,上传时间长的问题,需要将图片压缩上传,
(2)图片压缩比率因大小不同而不同。
(3)uniapp.compressImage不支持h5,而且只能压缩jpg文件
’本文使用uniapp的uni-file-picker进行图片上传,uview的图片上传也可以参考使用。
(1)先把图片都转换为jpg格式文件
(2 )然后计算压缩比率。压缩率compressorjs使用的范围是0-1,uniapp.compressImage使用的是0-100,需要转换下。
(3)最后h5压缩使用compressorjs,非h5压缩使用uniapp.compressImage。
(4)部署到服务器,修改nginx默认长传文件的大小
经验证,本程序只支持h5,小程序uniapp.compressImage只支持jpg文件。
如需支持h5,小程序,app,请转若依移动端Ruoyi-App——使用helang-compress组件压缩上传图片,支持App,小程序,h5,也支持各类格式图片文件。_鲸鱼姐的博客-CSDN博客
效果如下
npm install compressorjs --save
- import Compressor from 'compressorjs';
- // 只能对jpeg格式的图片进行转换
- /**
- * @param image 图片
- * @param backType 需要返回的类型blob,file
- * @param quality 图片压缩比 0-1,数字越小,图片压缩越小
- * @returns
- */
- export default function ImageCompressor(image, backType, quality) {
- return new Promise((resolve, reject) => {
- new Compressor(image, {
- quality: quality || 0.6,
- success(result) {
-
- let file = new File([result], image.name, { type: image.type })
- if (!backType || backType == 'blob') {
- resolve(result)
- } else if (backType == 'file') {
- resolve(file)
- } else {
- resolve(file)
- }
- },
- error(err) {
- console.log('图片压缩失败---->>>>>', err)
- reject(err)
- }
- })
- })
- }
-

- // 思路是创建一个图片,将file等于这个图片,然后创建一个canvas图层 ,将canvas等比例缩放,
- //然后用canvas的drawImage将图片与canvas合起来,然后在把canvas的base64转成file即可
- export default function ConvertImage(file) {
- return new Promise((resolve, reject) => {
- const fileName = file.name.substring(0, file.name.indexOf('.'));
- let reader = new FileReader(); //读取file
- reader.readAsDataURL(file);
- reader.onloadend = function (e) {
- let image = new Image() //新建一个img标签(还没嵌入DOM节点)
- image.src = e.target.result //将图片的路径设成file路径
- image.onload = function () {
- let canvas = document.createElement('canvas'),
- context = canvas.getContext('2d'),
- imageWidth = image.width,
- imageHeight = image.height,
- data = ''
- canvas.width = imageWidth
- canvas.height = imageHeight
-
- context.drawImage(image, 0, 0, imageWidth, imageHeight)
- data = canvas.toDataURL('image/jpeg')
- var newfile = dataURLtoFile(data, fileName + '.jpeg');
- resolve(newfile)
- }
- }
- })
- }
- function dataURLtoFile(dataurl, filename) { // base64转file对象
- let arr = dataurl.split(','),
- mime = arr[0].match(/:(.*?);/)[1],
- bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
- while (n--) {
- u8arr[n] = bstr.charCodeAt(n);
- }
- return new File([u8arr], filename, { type: mime }); //转成了jpeg格式
- }

3. 图片压缩页面的代码如下
- <template>
- <view class="u-page">
- <view class="u-demo-block">
- <view class="u-demo-block__content">
- <!-- 注意,如果需要兼容微信小程序,最好通过setRules方法设置rules规则 -->
- <u--form
- labelPosition="left"
- :model="form"
- ref="form1"
- >
- <u-form-item
- label="选择照片"
- prop="form.problemDescription"
- borderBottom
- labelWidth="80"
- ref="item3"
- >
- <uni-file-picker
- :source-type="sourceType"
- :sizeType="sizeType"
- v-model="fileList1"
- mode="grid"
- @select="select"
- @progress="progress"
- @success="success"
- @delete ="deletephoto"
- @fail="fail"
- ref="upload"
- limit="9"
- />
- </uni-file-picker>
- </u-form-item>
- </u--form>
- </view>
- </view>
- </view>
- </template>
-
- <script>
- import { getToken } from "@/utils/auth";
- import ImageCompressor from "@/utils/imageCompressor"
- import ConvertImage from "@/utils/ConvertImage"
- import config from '@/config'
- export default {
- data() {
- return {
- sourceType: ['album', 'camera'],
- sizeType: ['compressed'],
- fileMaxSize: 2 * 1024 * 1024, // 默认最大为2M
- fileMinSize: 50 * 1024, // 最小为50KB
- form: {},
- fileList1: {},
- imgSrc:{},
- images: [],
- }
- },
- onReady() {
-
- },
- mounted() {
- // this.nowTimes()
- },
- onLoad(option) {
-
- },
- methods: {
-
- // // 选择上传触发函数
- async select(e) {
- // 根据所选图片的个数,多次调用上传函数
- this.btndisabled = true;
- this.loadingflag = true;
- console.log("select")
- console.log(e.tempFilePaths)
- let promises=[]
-
- for (let i = 0; i < e.tempFilePaths.length; i++) {
-
- let imgtemp=e.tempFiles[i].file
- console.log('img')
- console.log(e)
- const fileName = imgtemp.name ?? ''
- let url =imgtemp.path
- const fileType = fileName.substring(fileName.indexOf('.') + 1);
- console.log(fileType)
- // 判断文件是不是jpeg 不是jpeg的都转成jpeg
- if (!['jpeg', 'jpg'].includes(fileType)) {
- console.log(fileType)
- imgtemp = await ConvertImage(imgtemp); //转陈jpeg格式的file
- }
-
- const fileSize = imgtemp.size
- if (fileSize > this.fileMaxSize) {
- const compressionRatio = this.getCompressionRatio(fileSize)
- if (compressionRatio > 1) {
- uni.$u.toast('文件' + fileName + '大于10M')
- return false
- }
- console.log('压缩前文件' + fileName + '==compressionRatio'+compressionRatio+'===大小'+fileSize)
- // #ifdef H5
- imgtemp = await ImageCompressor(imgtemp, 'blob', compressionRatio); //图片压缩
- console.log('压缩后文件' + imgtemp.fileName + '====大小'+imgtemp.size)
- url = window.URL.createObjectURL(imgtemp)
- // #endif
- // #ifndef H5
- this.compressImg(e.tempFilePaths[i],compressionRatio*100,url)
- // #endif
- }
- console.log('压缩后文件' + url)
- const promise =this.uploadFiles(url)
- promises.push(promise)
- }
- Promise.all(promises).then(()=>{
- })
- },
-
- // 图片压缩
- compressImg(tempFilePath,compressionRatio,url){
- uni.compressImage({
- src: tempFilePath,
- quality: compressionRatio,
- success: info => {
- url=info.tempFilePath
-
- }
- })
- },
- // 图片压缩比例计算
- getCompressionRatio(fileSize) {
- const multiple = (fileSize / this.fileMaxSize).toFixed(2) // 获取文件大小倍数,生成质量比
- let compressionRatio = 1
- if(multiple > 5) {
- compressionRatio = 0.5
- } else if (multiple > 4) {
- compressionRatio = 0.6
- } else if (multiple > 3) {
- compressionRatio = 0.7
- }else if (multiple > 2) {
- compressionRatio = 0.8
- } else if (multiple > 1) {
- compressionRatio = 0.9
- } else {
- compressionRatio = 2
- }
- return compressionRatio;
- },
- // 上传函数
- async uploadFiles(tempFilePath){
- const baseUrl = config.baseUrl
- let that =this
- await uni.uploadFile({
- url: baseUrl+'/common/upload', //后端用于处理图片并返回图片地址的接口
- filePath:tempFilePath,
- name: 'file',
- header: {
- Authorization: "Bearer " + getToken(),
- },
- success: res => {
- let data=JSON.parse(res.data) //返回的是字符串,需要转成对象格式
- let imageName=data.fileName
- that.images.push(imageName)
- console.log(that.images)
- uni.showToast({ title: '上传成功', icon: "success" });
- this.btndisabled = false;
- this.loadingflag = false;
- },
- fail: () => {
- console.log("上传失败");
- uni.showToast({ title: '上传失败', icon: "error" });
-
- }
- })
- },
- // 移出图片函数
- async deletephoto(){
- this.fileList1 = {}
- },
-
- submit() {
-
- console.log(this.images)
- this.form.problemPhotos=this.images.join(',');
- addProblems(this.form).then(response => {
- this.$modal.msgSuccess("新增成功");
-
- })
- }).catch(errors => {
- uni.$u.toast('请扫码,填写问题,上传照片')
- })
- },
-
- }
- }
- </script>
-

- getCompressionRatio(fileSize) {
- const multiple = (fileSize / this.fileMaxSize).toFixed(2) // 获取文件大小倍数,生成质量比
- alert(fileSize+"==="+this.fileMaxSize+"==="+multiple)
- let compressionRatio = 1
- if(multiple > 5) {
- compressionRatio = 0.5
- } else if (multiple > 4) {
- compressionRatio = 0.6
- } else if (multiple > 3) {
- compressionRatio = 0.7
- }else if (multiple > 2) {
- compressionRatio = 0.8
- } else if (multiple > 1) {
- compressionRatio = 0.9
- } else {
- compressionRatio = 2
- }
- return compressionRatio;
- },

- // #ifdef H5
- imgtemp = await ImageCompressor(imgtemp, 'blob', compressionRatio); //图片压缩
- console.log('压缩后文件' + imgtemp.fileName + '====大小'+imgtemp.size)
- url = window.URL.createObjectURL(imgtemp)
- // #endif
- // #ifndef H5
- this.compressImg(e.tempFilePaths[i],compressionRatio*100,url)
- // #endif
使用uni.uploadFile上传文件,filePath使用的是bloburl本地地址,blob:http://localhost:9092/e9a9042b-feab-4fed-99ff-81c1e6efdece
- uni.uploadFile({
- url: '/prod-api/common/upload', //后端用于处理图片并返回图片地址的接口
- filePath:tempFilePath,
- ...
-
- })
因此需要将压缩后的blob文件转换成bloburl,这样才能展示及上传
let url = window.URL.createObjectURL(newImg)
通过nginx发现服务代理的,问题就出现nginx服务器上,原来nginx默认长传文件的大小是1M,可在nginx的配置中修改。
解决方法:
(1)打开nginx服务的配置文件nginx.conf, 路径一般是:/usr/local/nginx/conf/nginx.conf。
(2)在http{}中加入client_max_body_size 100m,我这里配置的是100M。
http {
client_max_body_size 100m;
include mime.types;
default_type application/octet-stream;
(3)重新nginx服务。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。