(十)微信小程序---上傳圖片chooseImage 與 上傳到服務器


官方文檔

 

 

 

 

 

    

 

示例一

  • wxml
<view bindtap="uploadImage">請上傳圖片</view>

<image wx:for="{{imageList}}" src="{{item}}"></image>
  • 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)
        })
      },
    })
  },
})

 

 

 上傳到服務器

 我們的例子是 騰訊雲的存儲  https://console.cloud.tencent.com/cos5

 

 1. 創建存儲桶

 

 

 

 

2. 小程序上傳的文檔

https://cloud.tencent.com/document/product/436/31953

 

 

 下載好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 = new COS({ 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); }); } },
})

 

 上面我們說的是官方不推薦使用的一種方法,現在說一種推薦使用的方式

 

 

 

 

https://cloud.tencent.com/document/product/436/14048

開始咯

官網代碼獲取臨時秘鑰
var
cos = new COS({ // 必選參數 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
拷貝源碼https://github.com/tencentyun/qcloud-cos-sts-sdk/blob/master/python/demo/sts_demo.py
from django.conf.urls import url
from app01 import views
urlpatterns = [
    # 獲取秘鑰
    url(r'^credential/', views.CredentialView.as_view()),
]


class CredentialView(APIView):
    def get(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)

然后你訪問網址

 

 我們只需要把上面的網址放在開始咯處的網址那即可

 

 

 

 上傳成功

 

 





 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM