uniapp 非图片格式文件上传七牛

本文介绍了一个小程序中实现文件上传功能的详细过程,包括利用七牛云进行文件上传、预览和处理上传进度的方法。通过创建文件输入元素并监听其变化,可以获取到附件本身,并将其转换为Base64格式进行预览。同时,文章还展示了如何使用七牛云的SDK进行文件上传,以及如何处理上传成功和失败的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<template>
	<view class="container wrap">
		<!-- 附件 -->
		<view class="cu-list menu">
			<view class="cu-item fj">
				<view class="content"><text>附件:</text></view>
				<view class="action text-left"><view ref="input" class="input"></view></view>
			</view>
		</view>
	</view>
</template>

<script>
import qiniu from '../../static/js/qiniuUploader.js';
var that;
export default {
	data() {
		return {
			readOnly: false,
			formats: {},
			infoType: false,
			radio: 0,
			levelList: [],
			levelName: '',
			statusColor: '',
			themeList: [],
			themeIndex: 998,
			personnelIds: [],
			departIds: [],
			mailTitle: '',
			upToken: '',
			imgSrc: '',
			contextValue: '',
			attachmentName: '', //附件name
			attachmentUrl: '' //附件URL
		};
	},
	mounted() {
		//创建file
		var input = document.createElement('input');
		input.type = 'file';
		input.onchange = event => {
			// event.path[0].files[0] 附件本身
			console.log(event.path[0].files[0]);
			console.log(event);
			that.attachmentName = event.path[0].files[0].name;
			that.previewFile(event.path[0].files[0]);
		};
		this.$refs.input.$el.appendChild(input);
	},
	onLoad(option) {
		that = this;
		// 获取上传token
		that.getUploadToken();
		// 每隔两小时  更新token
		setInterval(function() {
			that.getUploadToken();
		}, 2 * 60 * 60 * 1000);
	},
	methods: {
		previewFile(file) {
			var reader = new FileReader();

			reader.onloadend = function() {
				console.log(reader.result);
				console.log(that.dataURLtoFile(reader.result, file.name));
				console.log(URL.createObjectURL(that.dataURLtoFile(reader.result, file.name)));
				let url = URL.createObjectURL(that.dataURLtoFile(reader.result, file.name));
				that.uploadFile(url, file.name);
			};
			reader.readAsDataURL(file);
		},
		dataURLtoFile(dataurl, filename) {
			//将base64转换为blob
			var arr = dataurl.split(',');
			var bstr = atob(arr[1]);
			var n = bstr.length;
			var mime = arr[0].match(/:(.*?);/)[1];
			var u8arr = new Uint8Array(n);
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n);
			}
			return new Blob([u8arr], { type: mime });
		},
		//上传文件
		uploadFile(file, fileName) {
			uni.showLoading({
				title: '上传附件中...'
			});
			console.log(that.upToken);
			qiniu.upload(
				file,
				fileName,
				res => {
					//图片上传完成后返回值
					console.log('success');
					console.log(JSON.stringify(res));
					console.log(res);
					that.attachmentUrl = res.fileURL;
					uni.hideLoading();
				},
				error => {
					// resolve(error)
					console.log('error');
					console.log(error);
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						title: '上传失败'
					});
				},
				{
					region: 'SCN', // (必须填写正确)ECN, SCN, NCN, NA, ASG,分别对应七牛的:华东,华南,华北,北美,新加坡 5 个区域
					domain: 'http://waimao.share.xinhai.com', // // bucket 域名,下载资源时用到。如果设置,会在 success callback 的 res 参数加上可以直接使用的 ImageURL                                         字  段。否则需要自己拼接
					// 以下方法三选一即可,优先级为:uptoken > uptokenURL > uptokenFunc
					uptoken: that.upToken // 由其他程序生成七牛 uptoken
				},
				res => {
					//上传进度
					if (res.progress === 100) {
						console.log(res);
						// resolve(keys);
						console.log('进度');
						// console.log(resolve(keys))
					}
				}
			);
		},
		// 获取token
		getUploadToken() {
			if (that.upToken) {
				return false;
			}
			uni.request({
				url: that.requestUrl + 'auth/upToken',
				header: {
					Authorization: that.token
				},
				method: 'get',
				success(data) {
					console.log(data);
					console.log(data.data);
					if (data.data.code == 0) {
						console.log(data.data.data);
						that.upToken = data.data.data;
					} else {
						uni.showToast({
							icon: 'none',
							title: data.msg,
							duration: 2000
						});
					}
				},
				fail(error) {
					uni.showToast({
						icon: 'none',
						title: '数据加载失败',
						duration: 2000
					});
					console.log(error);
				}
			});
		}
	}
};
</script>

<style scoped lang="scss">

</style>

### UniApp 中实现图片上传为 Blob 格式的方案 在 UniApp 开发环境中,为了高效地处理并上传图片文件,在前端可以先对图片进行适当预处理再转换成 Blob 对象以便于后续操作。对于 H5 平台而言,可以通过 `canvas` 或者直接利用 Base64 编码的数据来创建 Blob。 当采用 canvas 进行图像处理时,比如通过调用 `uni.canvasToTempFilePath()` 方法获取临时路径之后,可进一步读取该文件内容作为二进制数据流用于构建 Blob 实体[^1]。另一种常见方式是在拥有 base64 编码字符串的情况下借助辅助函数将其解析为实际的二进制对象,如下所示: ```javascript function base64ToBlob(b64Data, contentType='') { const sliceSize = 512; b64Data = b64Data.replace(/^[^,]+,/, ''); b64Data = atob(b64Data); let byteArrays = []; for (let offset = 0; offset < b64Data.length; offset += sliceSize) { let slice = b64Data.slice(offset, offset + sliceSize); let byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } let byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } return new Blob(byteArrays, {type: contentType}); } ``` 此段 JavaScript 函数能够接收包含 MIME 类型前缀在内的完整的 Base64 字符串以及指定的内容类型参数,并返回对应的 Blob 对象实例[^2]。一旦获得了 Blob 形式的资源表示形式,则可通过 XMLHttpRequest 或 Fetch API 将其提交至服务器端完成最终存储过程。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值