
<template><view class="content"><button type="default" @click="selectUpload">Select Files to Upload</button><image v-if="fileUrl" class="image" :src="fileUrl"></image></view></template><script>export default {data() {return {title: 'Hello',fileUrl: ''};},onLoad() {},methods: {selectUpload() {var vm = this;// url encode format for encoding more charactersvar camSafeUrlEncode = function (str) {return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\\(/g, '%28').replace(/\\)/g, '%29').replace(/\\*/g, '%2A');};// Obtain the upload path and upload credentialsvar getUploadInfo = function (extName, callback) {// Pass in the file suffix to let the backend generate a random COS object path, and return the upload domain name and policy signature required for the PostObject interface// Server example reference: https://github.com/tencentyun/cos-demo/tree/main/server/post-policyuni.request({url: 'http://127.0.0.1:3000/post-policy?ext=' + extName,success: (res) => {// Check whether the return format is correctconsole.log(res);callback && callback(null, res.data);},error(err) {callback && callback(err);},});};// Initiate the upload request using the PostObject interface with policy signature protection// Interface documentation: https://www.tencentcloud.com/document/product/436/14690#.E7.AD.BE.E5.90.8D.E4.BF.9D.E6.8A.A4var uploadFile = function (opt, callback) {var formData = {key: opt.cosKey,policy: opt.policy, // This passes the base64 string of the policysuccess_action_status: 200,'q-sign-algorithm': opt.qSignAlgorithm,'q-ak': opt.qAk,'q-key-time': opt.qKeyTime,'q-signature': opt.qSignature,};// If the server uses temporary key calculation, you need to pass x-cos-security-tokenif (opt.securityToken) formData['x-cos-security-token'] = opt.securityToken;uni.uploadFile({url: 'https://' + opt.cosHost, // This is only an example, not a real interface addressfilePath: opt.filePath,name: 'file',formData: formData,success: (res) => {if (![200, 204].includes(res.statusCode)) return callback && callback(res);var fileUrl = 'https://' + opt.cosHost + '/' + camSafeUrlEncode(opt.cosKey).replace(/%2F/g, '/');callback && callback(null, fileUrl);},error(err) {callback && callback(err);},});};// Select fileuni.chooseImage({success: (chooseImageRes) => {var file = chooseImageRes.tempFiles[0];if (!file) return;// Obtain the local file path to be uploadedvar filePath = chooseImageRes.tempFilePaths[0];// Obtain the file suffix to be uploaded, and let the backend generate a random COS object pathvar fileName = file.name;var lastIndex = fileName.lastIndexOf('.');var extName = lastIndex > -1 ? fileName.slice(lastIndex + 1) : '';// Obtain domain, path, and credentials for pre-upload.getUploadInfo(extName, function (err, info) {// Confirm whether the info format is correctconsole.log(info);// Upload documents.info.filePath = filePath;uploadFile(info, function (err, fileUrl) {vm.fileUrl = fileUrl;});});}});},}}</script><style>.content {padding: 20px 0;display: flex;flex-direction: column;align-items: center;justify-content: center;}.image {margin-top: 20px;margin-left: auto;margin-right: auto;}</style>
<template><view class="content"><button type="default" @click="selectUpload">Select Files to Upload</button><image v-if="fileUrl" class="image" :src="fileUrl"></image></view></template><script>export default {data() {return {title: 'Hello',fileUrl: ''};},onLoad() {},methods: {selectUpload() {var vm = this;// url encode format for encoding more charactersvar camSafeUrlEncode = function (str) {return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\\(/g, '%28').replace(/\\)/g, '%29').replace(/\\*/g, '%2A');};// Obtain the upload path and upload credentialsvar getUploadInfo = function (extName, callback) {// Pass in the file suffix to let the backend generate a random COS object path, and return the signature required for the PUT Object interface// backend needs to return: cosHost, cosKey, authorization, securityToken (optional)uni.request({url: 'http://127.0.0.1:3000/put-signature?ext=' + extName,success: (res) => {// Check whether the return format is correctconsole.log(res);callback && callback(null, res.data);},fail(err) {callback && callback(err);},});};// Read file as ArrayBuffervar readFileAsArrayBuffer = function (filePath, callback) {uni.getFileSystemManager().readFile({filePath: filePath,success: (res) => {callback && callback(null, res.data); // res.data is ArrayBuffer},fail(err) {callback && callback(err);}});};// Initiate the upload request using the PUT Object interface// Interface documentation: https://www.tencentcloud.com/document/product/436/7749var uploadFile = function (opt, fileData, callback) {var headers = {'Authorization': opt.authorization, // Signature'Content-Type': opt.contentType || 'application/octet-stream'};// If the server uses temporary key calculation, you need to pass x-cos-security-tokenif (opt.securityToken) {headers['x-cos-security-token'] = opt.securityToken;}console.log('Upload request information:', {url: 'https://' + opt.cosHost + '/' + opt.cosKey,headers: headers});uni.request({url: 'https://' + opt.cosHost + '/' + opt.cosKey,method: 'PUT',header: headers,data: fileData, // in ArrayBuffer formatsuccess: (res) => {console.log('Upload response:', res);if (![200, 204].includes(res.statusCode)) {console.error('Upload failed, status code:', res.statusCode);return callback && callback(res);}var fileUrl = 'https://' + opt.cosHost + '/' + camSafeUrlEncode(opt.cosKey).replace(/%2F/g, '/');callback && callback(null, fileUrl);},fail(err) {console.error('Upload request failed:', err);callback && callback(err);},});};// Select fileuni.chooseImage({success: (chooseImageRes) => {var file = chooseImageRes.tempFiles[0];if (!file) return;// Obtain the local file path to be uploadedvar filePath = chooseImageRes.tempFilePaths[0];// Obtain the file suffix to be uploaded, and let the backend generate a random COS object pathvar fileName = file.name;var lastIndex = fileName.lastIndexOf('.');var extName = lastIndex > -1 ? fileName.slice(lastIndex + 1) : '';// Obtain the domain, path, and signature for pre-uploadgetUploadInfo(extName, function (err, info) {if (err) {console.error('Failed to obtain upload information:', err);return;}// Confirm whether the info format is correctconsole.log(info);// Read file as ArrayBufferreadFileAsArrayBuffer(filePath, function (err, fileData) {if (err) {console.error('Failed to read the file:', err);return;}// Upload documents.uploadFile(info, fileData, function (err, fileUrl) {if (err) {console.error('Upload failed:', err);return;}vm.fileUrl = fileUrl;console.log('Upload succeeded:', fileUrl);});});});}});},}}</script><style>.content {padding: 20px 0;display: flex;flex-direction: column;align-items: center;justify-content: center;}.image {margin-top: 20px;margin-left: auto;margin-right: auto;}</style>


Feedback