微信小程序上传图片到服务器总是失败_(十)微信小程序---上传图片chooseImage 与 上传到服务器...

本文介绍了如何在微信小程序中实现图片选择并上传到服务器。首先展示了使用`wx.chooseImage`接口选择图片,并通过`setData`更新列表。接着讨论了如何在列表中添加新图片,使用`concat`方法合并数组。随后,详细阐述了将图片上传到腾讯COS服务器的过程,包括创建存储桶、使用官方SDK以及获取临时密钥的方法。最后,提供了服务端获取临时密钥的示例代码。
摘要由CSDN通过智能技术生成

示例一

wxml

请上传图片

js

Page({/**

* 页面的初始数据*/data: {

imageList:["/static/default.png","/static/default.png","/static/default.png",

]

},

uploadImage:function(){var that = this;

wx.chooseImage({

count:9,                   // 最多可以选择的图片张数

sizeType: ['original', 'compressed'], // 选择图片的尺寸

sourceType: ['album', 'camera'], // 选择图片的来源

success: function(res) {

that.setData({

imageList:res.tempFilePaths

})

},

})

},

})

示例二

如上 我们有原来的三张图 我们现在在选两张 是要添加进去 如何做?

先学习一下js的知识

1. 列表里添加  push

v1=[1,2]

>>> (2) [1, 2]

v1.push(3)v1

>>>(3) [1, 2, 3]

2. 合并列表 concat

v1=[1,2,3]

>>>(2) [1, 2, 3]v2=[5,6]

>>>(2) [5, 6]

v1.concat(v2)

>>>(5) [1, 2, 3, 5, 6]

微信中添加照片

Page({data: {

imageList:["/static/default.png","/static/default.png","/static/default.png",

]

},

uploadImage:function(){var that = this;

wx.chooseImage({

count:9,

sizeType: ['original', 'compressed'],

sourceType: ['album', 'camera'],

success: function(res) {

that.setData({

imageList:that.data.imageList.concat(res.tempFilePaths)

})

},

})

},

})

上传到服务器

1. 创建存储桶

2. 小程序上传的文档

下载好js代码 我们就可以直接用了

3. 开始使用

4.配置项--- 也就是上传配置

官方文档给了四种方式

我们先使用第四种---不推荐

好了 我们的代码

var COS = require('./../../utils/cos-wx-sdk-v5.js')

Page({

data: {

imageList: []

},

上传文件的代码

uploadImage:function(){var that = this;

wx.chooseImage({

count:9,

sizeType: ['original', 'compressed'],

sourceType: ['album', 'camera'],

success: function (res) {

that.setData({

imageList: that.data.imageList.concat(res.tempFilePaths)

})

},

})

},

发布的代码

uploadImageFile:function(){var cos = newCOS({

SecretId:'******',

SecretKey:'*****',

});for(var index in this.data.imageList){

循环得到图片地址var filePath = this.data.imageList[index]

自己做文件的名字var filename = filePath.substr(filePath.lastIndexOf('/')+1);

cos.postObject({

// 桶的名字

Bucket:'upload-******',

Region:'ap-chengdu',

Key: filename,

FilePath: filePath,

onProgress: function (info) {//上传可以写进度条

console.log(JSON.stringify(info));

}

}, function (err, data) {

console.log(err||data);

});

}

},

})

上面我们说的是官方不推荐使用的一种方法,现在说一种推荐使用的方式

开始咯

官网代码获取临时秘钥

var cos = newCOS({//必选参数

getAuthorization: function (options, callback) {//服务端 JS 和 PHP 示例:https://github.com/tencentyun/cos-js-sdk-v5/blob/master/server/

//服务端其他语言参考 COS STS SDK :https://github.com/tencentyun/qcloud-cos-sts-sdk ① 点击

//STS 详细文档指引看:https://cloud.tencent.com/document/product/436/14048

wx.request({

url:'https://example.com/server/sts.php',

data: {//可从 options 取需要的参数

},

success: function (result) {var data =result.data;var credentials =data.credentials;

callback({

TmpSecretId: credentials.tmpSecretId,

TmpSecretKey: credentials.tmpSecretKey,

XCosSecurityToken: credentials.sessionToken,

ExpiredTime: data.expiredTime,

});

}

});

}

});

注释:

① 点击:点击上面的网址找到python相关 按文档操作【安装 拷贝源码】

pip install -U qcloud-python-sts

fromdjango.conf.urls import urlfromapp01 import views

urlpatterns=[

# 获取秘钥

url(r'^credential/', views.CredentialView.as_view()),

]classCredentialView(APIView):

defget(self, request, *agrs, **kwargs):

config={

# 临时密钥有效时长,单位是秒'duration_seconds': 1800,'secret_id': '***********',

# 固定密钥'secret_key': '***********',

# 设置网络代理

#'proxy': {

#'http': 'xx',

#'https': 'xx'# },

# 换成你的 bucket'bucket': 'upload-*********',

# 换成 bucket 所在地区'region': 'ap-chengdu',

# 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径

# 例子: a.jpg 或者 a/*或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)

'allow_prefix': '*',

# 密钥的权限列表。简单上传和分片需要以下的权限,其他权限列表请看https://cloud.tencent.com/document/product/436/31923'allow_actions': [

# 简单上传

# 'name/cos:PutObject',

'name/cos:PostObject',

# 分片上传

# 'name/cos:InitiateMultipartUpload',

# 'name/cos:ListMultipartUploads',

# 'name/cos:ListParts',

# 'name/cos:UploadPart',

# 'name/cos:CompleteMultipartUpload'

],

}

try:

sts = Sts(config)

response = sts.get_credential()

print('get data : ' + json.dumps(dict(response), indent=4))

except Exception as e:

print(e)

return Response(response)

然后你访问网址

我们只需要把上面的网址放在开始咯处的网址那即可

上传成功

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值