uni-app 图片上传七牛云
前台uni-app+colorUi后台jeecgboot前台直接使用colorui实现的效果上传到七牛直接使用colorui实现的效果代码<view class="cu-bar bg-white margin-top"><view class="action">图片上传</view><view class...
·
前台uni-app+colorUi
后台jeecgboot
-
思路
- 用colorui能实现效果,但是路径还是指向本地
- 用七牛云,先上传到七牛云,返回路径并且指向它
- 后台去获取七牛token并且返回(最后后台java代码)
- 根据token上传图片
export const uploadImage = (num, callback) => {
uni.chooseImage({
count: num,
success: (res) => {
uni.showLoading({
title: '上传中...'
});
let tempFilePaths = res.tempFilePaths
console.log(tempFilePaths)
//获取token
get('/subject/projectSubject/getToken',null,resto=>{
//我这里只有获取到一个key token 只能一张一张上传
console.log(resto)
for (var i = 0; i < tempFilePaths.length; i++) {
uni.uploadFile({
url: 'https://up.qbox.me',//华东地区用这个
filePath: tempFilePaths[i],
name: 'file',
formData: {
'key': resto.result.key,
'token': resto.result.token
},
success: (uploadFileRes) => {
console.log(uploadFileRes)
//qiniuUrl是自己七牛的前缀
callback(qiniuUrl+JSON.parse(uploadFileRes.data).key);
},
fail: (error) => {
if (error && error.response) {
showError(error.response);
}
},
complete: () => {
setTimeout(function() {
uni.hideLoading();
}, 250);
},
});
}
})
}
});
}
直接使用colorui实现的效果
代码
<view class="cu-bar bg-white margin-top">
<view class="action">
图片上传
</view>
<view class="action">
{{imgList.length}}/4
</view>
</view>
<view class="cu-form-group">
<view class="grid col-4 grid-square flex-sub">
<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
<image :src="imgList[index]" mode="aspectFill"></image>
<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
<text class='cuIcon-close'></text>
</view>
</view>
<view class="solids" @tap="ChooseImage" v-if="imgList.length<4">
<text class='cuIcon-cameraadd'></text>
</view>
</view>
</view>
data中声明
imgList: []
声明方法
ChooseImage() {
uni.chooseImage({
count: 4, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: (res) => {
if (this.imgList.length != 0) {
this.imgList = this.imgList.concat(res.tempFilePaths)
} else {
this.imgList = res.tempFilePaths
}
}
});
},
//浏览大图
ViewImage(e) {
uni.previewImage({
urls: this.imgList,
current: e.currentTarget.dataset.url
});
},
DelImg(e) {
uni.showModal({
title: '召唤师',
content: '确定要删除这段回忆吗?',
cancelText: '再看看',
confirmText: '再见',
success: res => {
if (res.confirm) {
this.imgList.splice(e.currentTarget.dataset.index, 1)
}
}
})
},
就可以实现预览的效果,但是他是本地的,接下来进入正题
上传到七牛
写一个公共的方法
export const uploadImage = (num, callback) => {
uni.chooseImage({
count: num,
success: (res) => {
uni.showLoading({
title: '上传中...'
});
let tempFilePaths = res.tempFilePaths
console.log(tempFilePaths)
//获取token
get('/subject/projectSubject/getToken',null,resto=>{
//我这里只有获取到一个key token 只能一张一张上传
console.log(resto)
for (var i = 0; i < tempFilePaths.length; i++) {
uni.uploadFile({
url: 'https://up.qbox.me',//华东地区用这个
filePath: tempFilePaths[i],
name: 'file',
formData: {
'key': resto.result.key,
'token': resto.result.token
},
success: (uploadFileRes) => {
console.log(uploadFileRes)
//qiniuUrl是自己七牛的前缀
callback(qiniuUrl+JSON.parse(uploadFileRes.data).key);
},
fail: (error) => {
if (error && error.response) {
showError(error.response);
}
},
complete: () => {
setTimeout(function() {
uni.hideLoading();
}, 250);
},
});
}
})
}
});
}
调用的地方变成
ChooseImage() {
var that=this
this.$config.uploadImage(5, res => {
if (!that.imgList) {
that.imgList = []
}
this.imgList = this.imgList.concat(res)
that.$common.successToShow("上传成功")
})
}
获取token java后台
package org.jeecg.common.util;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.util.StringUtils;
import java.io.IOException;
public class QiNiuUtil {
// 设置需要操作的账号的AK和SK
private static final String ACCESS_KEY = "";
private static final String SECRET_KEY = "";
// 要上传的空间
private static final String bucketname = "";
// 密钥
private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
private static final String DOMAIN = "";
private static final String style = "自定义的图片样式";
public String getUpToken() {
return auth.uploadToken(bucketname, null, 3600, new StringMap().put("insertOnly", 1));
}
// 普通上传
public String upload(String filePath, String fileName) throws IOException {
//要上传的空间(bucket)的存储区域为华东时
Zone z = Zone.zone0();
//密钥配置
Configuration c = new Configuration(z);
// 创建上传对象
UploadManager uploadManager = new UploadManager(c);
try {
// 调用put方法上传
String token = auth.uploadToken(bucketname);
if(StringUtils.isEmpty(token)) {
System.out.println("未获取到token,请重试!");
return null;
}
Response res = uploadManager.put(filePath, fileName, token);
// 打印返回的信息
System.out.println(res.bodyString());
if (res.isOK()) {
Ret ret = res.jsonToObject(Ret.class);
//如果不需要对图片进行样式处理,则使用以下方式即可
return DOMAIN + ret.key;
// return DOMAIN + ret.key + "?" + style;
}
} catch (QiniuException e) {
Response r = e.response;
// 请求失败时打印的异常的信息
System.out.println(r.toString());
try {
// 响应的文本信息
System.out.println(r.bodyString());
} catch (QiniuException e1) {
// ignore
}
}
return null;
}
//根据key获取token
public String getToken(String key) throws IOException {
String token = auth.uploadToken(bucketname,key);
if(StringUtils.isEmpty(token)) {
System.out.println("未获取到token,请重试!");
return null;
}
return token;
}
//base64方式上传
public String put64image(byte[] base64, String key) throws Exception{
String file64 = Base64.encodeToString(base64, 0);
Integer l = base64.length;
String url = "http://upload.qiniu.com/putb64/" + l + "/key/"+ UrlSafeBase64.encodeToString(key);
//非华东空间需要根据注意事项 1 修改上传域名 重点我之前手贱过
RequestBody rb = RequestBody.create(null, file64);
Request request = new Request.Builder().
url(url).
addHeader("Content-Type", "application/octet-stream")
.addHeader("Authorization", "UpToken " + getUpToken())
.post(rb).build();
//System.out.println(request.headers());
OkHttpClient client = new OkHttpClient();
okhttp3.Response response = client.newCall(request).execute();
System.out.println(response);
//如果不需要添加图片样式,使用以下方式
return DOMAIN + key;
// return DOMAIN + key + "?" + style;
}
// 普通删除使用时删除成功但还是能访问到,查了说是七牛云缓存,解决办法没
public void delete(String key) throws IOException {
//要上传的空间(bucket)的存储区域为华东时
Zone z = Zone.zone0();
//密钥配置
Configuration c = new Configuration(z);
// 实例化一个BucketManager对象
BucketManager bucketManager = new BucketManager(auth,c);
// 我直接取的最后一个/如果有分支的话请改变这里的index
int index=key.lastIndexOf('/');
key = key.substring(index+1);
System.out.println(key);
try {
// 调用delete方法移动文件
bucketManager.delete(bucketname, key);
} catch (QiniuException e) {
// 捕获异常信息
Response r = e.response;
System.out.println(r.toString());
}
}
class Ret {
public long fsize;
public String key;
public String hash;
public int width;
public int height;
}
}
更多推荐
已为社区贡献7条内容
所有评论(0)