赞
踩
- <template>
- <view>
- <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" :maxCount="maxCount"
- :previewFullImage="true" @oversize="oversize($event)" multiple :maxSize="15728640">
- </u-upload>
- <!-- 添加水印虚拟结点 -->
- <!-- <view style="width: 0px; height: 0px; overflow: hidden">
- <canvas :style="'width: '+canvasWidth+'px; height:'+canvasHeight+'px;left:8888px'" canvas-id="myCanvas"></canvas>
- </view> -->
- </view>
- </template>
-
- <script>
- import getCurrentLngAndLat from "@/utils/getAddressLocation.js"
- import {
- HTTP_URL,
- HTTP_TEST_URL,
- HTTP_DEV_URL
- } from '@/const/host'
- export default {
- name: "UploadComponent",
- props: {
- maxCount: {
- type: Number,
- default: 1
- },
- name: {
- type: String,
- required: true
- },
- editUrl: {
- type: Array,
- default: () => {
- []
- }
- },
- types: {
- type: String,
- default: 'electronic'
- },
- },
- data() {
- return {
- fileList: [],
- src: '',
- canvasWidth: 0,
- canvasHeight: 0,
- address: '',
- lng: null,
- lat: null
- };
- },
- mounted() {
- // 判断是否存在编辑 URL
- if (this.editUrl) {
- // 将编辑 URL 添加到 fileList 中
- if (this.editUrl[0]?.url === '' || this.editUrl[0]?.url === null) {
- this.fileList = []
- } else {
- this.fileList = this.editUrl
- }
- };
- },
- watch: {
- editUrl: {
- immediate: true,
- handler(newVal, oldVal) {
- if (this.editUrl[0]?.url === '' || this.editUrl[0]?.url === null) {
- this.fileList = []
- } else {
- this.fileList = this.editUrl
- }
- }
- }
- },
- methods: {
- deletePic(event) {
- this.fileList.splice(event.index, 1);
- this.$emit("filesSelected", {
- name: this.name,
- fileList: this.fileList
- });
- },
- oversize(event) {
- uni.$showMsg('图片大小超过最大限制', 'none')
- },
- async afterRead(event) {
- const lists = [].concat(event.file);
- const fileListLen = this.fileList.length;
- for (let i = 0; i < lists.length; i++) {
- const item = lists[i]
- const results = await this.getCurrentLngAndLats();//获取当前定位
- let waterUrl = await this.addWatermark(item.url, address);
- this.fileList.push({
- ...item,
- status: "uploading",
- message: "上传中"
- });
- this.$emit("changLoad", true);
- try {
- const result = await this.uploadFilePromise(waterUrl,results); //上传图片
- await this.saveImage(result); //保存图片
- const uploadedItem = Object.assign({}, item, {
- status: "success",
- message: "",
- url: result
- });
- this.fileList.splice(fileListLen + i, 1, uploadedItem);
- this.$emit("changLoad", false);
- } catch (error) {
- const failedItem = Object.assign({}, item, {
- status: "fail",
- message: "上传失败"
- });
- this.fileList.splice(fileListLen + i, 1, failedItem);
- }
- }
- this.$emit("filesSelected", {
- name: this.name,
- fileList: this.fileList
- });
- },
- uploadFilePromise(url,lngLat) {
- console.log(lngLat,'000')
- // 初始化请求配置项
- let host = "";
- let envVs = uni.getAccountInfoSync().miniProgram.envVersion;
- if (envVs === 'release') {
- host = uni.getStorageSync('normal_url')
- } else if (envVs === 'trial') {
- host = uni.getStorageSync('exp_url')
- } else if (envVs === 'develop') {
- host = uni.getStorageSync('test_url')
- }
- // if (envVs === "release") {
- // host = HTTP_URL;
- // } else if (envVs === "trial") {
- // host = HTTP_TEST_URL;
- // } else if (envVs === "develop") {
- // host = HTTP_DEV_URL;
- // }
- return new Promise((resolve, reject) => {
- // wx.compressImage({
- // src: url,
- // quality: 90, // 压缩质量,范围为 0 - 100
- // success(res) {
- // const compressedFilePath = res.tempFilePath;
- uni.uploadFile({
- url: host + '/api/saler/v1/hhh', // 仅为示例,非真实的接口地址
- filePath: url,
- name: 'file',
- formData: {
- type: this.types,
- lat: lngLat.lat,
- lng: lngLat.lng,
- },
- header: {
- Authorization: 'Bearer ' + uni.getStorageSync('token')
- },
- success: async (res) => {
- if (res.statusCode === 200) {
- let arr = JSON.parse(res?.data);
- if (arr?.code == 0) {
- uni.$showMsg('上传失败', 'none');
- resolve('');
- } else {
- resolve(arr.data?.url);
- }
- } else {
- uni.$showMsg('上传失败', 'none');
- resolve('');
- }
- }
- })
- // },
- // fail(err) {
- // console.error('图片压缩失败:', err);
- // }
- // })
- });
- },
- //添加水印
- async addWatermark(img, address) {
- const image = img;
- let res1 = await new Promise((resolve, reject) => {
- uni.getImageInfo({
- src: img,
- success: (res) => {
- // 设置canvas宽高等于原图片宽高
- this.canvasWidth = res.width;
- console.log(Math.floor(res.width * 0.4), 'Math.floor(res.width*0.4)')
- this.canvasHeight = res.height;
- // 创建 canvas 的绘图上下文
- const ctx = uni.createCanvasContext('myCanvas', this);
- // 绘制图片
- ctx.drawImage(image, 0, 0, this.canvasWidth, this.canvasHeight);
- // 设置水印颜色大小
- ctx.setFillStyle('pink');
- ctx.setFontSize(Math.floor(res.width * 0.05));
- // 水印文字
- let time = new Date().toLocaleString();
- // 绘制水印文字
- ctx.fillText(time, 10, res.height * 0.75);
- // ctx.fillText(address, 10, res.height * 0.7);
- this.drawWatermark(ctx, '哈哈哈红红火火恍恍惚惚红红火火恍恍惚惚红红火火恍恍惚惚哈哈哈哈', 10, res.height * 0.85, res.width *
- 0.8)
- // 画到 canvas 中
- ctx.draw(false, () => {
- // 将画布转化为图片
- uni.canvasToTempFilePath({
- canvasId: 'myCanvas',
- success: (res) => {
- resolve(res.tempFilePath);
- },
- fail: (err) => {
- reject(err);
- }
- }, this);
- });
- }
- });
- });
- return (res1);
- },
- // 绘制水印文字
- drawWatermark(ctx, text, x, y, maxWidth) {
- let words = text.split('');
- let line = '';
- for (let n = 0; n < words.length; n++) {
- let testLine = line + words[n] + '';
- let metrics = ctx.measureText(testLine);
- let testWidth = metrics.width;
- if (testWidth > maxWidth && n > 0) {
- ctx.fillText(line, x, y);
- line = words[n] + '';
- y += y * 0.08;
- console.log(y, 'y')
- } else {
- line = testLine;
- }
- }
- ctx.fillText(line, x, y);
- },
- //保存图片
- saveImage(path) {
- uni.downloadFile({ //下载
- url: path,
- success: (res) => {
- uni.saveImageToPhotosAlbum({
- filePath: res.tempFilePath,
- success: () => {
- uni.$showMsg('保存成功', 'none');
- },
- // fail: (err) => {
- // uni.$showMsg('保存失败', 'none');
- // }
- })
- }
- })
- },
- getCurrentLngAndLats: async () => {
- const res = await getCurrentLngAndLat();
- return res;
- },
- }
- };
- </script>
-
- <style scoped>
- </style>

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。