1. 程式人生 > >tornado+vue實現上傳檔案

tornado+vue實現上傳檔案

要用tornado+vue寫一個後臺管理系統,記錄一下遇到檔案上傳時候的步驟:

1.Form表單裡的程式碼:(這裡是使用的餓了麼表單元件)

 <el-form-item label="頭像">
            <el-upload
                    class="avatar-uploader"//上傳框框的樣式
                    v-bind:action="FileUploadInterface"//這是請求後臺的介面
                    //是否展示圖片列表形式                    
                    :show-file-list="false"
                    :on-success="fund_manager_image_on_success"//介面呼叫成功之後的方法
                    //上傳檔案之前的判斷方法,校驗是否符合上傳規範                    
                    :before-upload="fund_manager_image_before_upload">
                    //如果表單物件有圖片,展示出來,沒有展示要上傳圖示樣式
                   <img v-if="formData.image" :src="formData.image" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            //展示圖片地址
            <el-input v-model="formData.image"></el-input>

       </el-form-item>

2.method裡面的方法:

//圖片格式校驗
 fund_manager_image_before_upload (file) {
      const isJPG =
              (file.name.endsWith('.JPG')) || (file.name.endsWith('.jpg')) ||
              (file.name.endsWith('.jpeg')) || (file.name.endsWith('.jpeg')) ||
              (file.name.endsWith('.PNG')) || (file.name.endsWith('.png'))
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isJPG) {
        this.$message.error('上傳檔案格式不正確!')
      }
      if (!isLt2M) {
        this.$message.error('上傳頭像圖片大小不能超過 10MB!')
      }
      if (isJPG && isLt2M) {
        this.formData.image = ' '
      }
      return isJPG && isLt2M
    },
    //上傳完成後的判斷
    fund_manager_image_on_success (sss, item) {
      if (sss != null && sss.success) {
        this.formData.image = sss.data.src
      } else {
        this.formData.image = ''
      }
    }

3.後端程式碼(這裡MyRequestHandler是做了處理,直接RequestHandler也可)

#上傳檔案介面
class FileUploadInterface(MyRequestHandler):
    #tornado的一個get請求
    def post(self):
        print("請求到了")
        # 判斷上傳檔案大小
        size = int(self.request.headers.get('Content-Length'))
        print('圖片大小:kb',size/1000)
        if size / 1000.0 > 2000:
            self.write("上傳圖片不能大於2M.")
            #獲取請求裡的檔案
        imgfiles = self.request.files.get('file')
        if imgfiles is not None and len(imgfiles)>0:
            #單檔案
            img=imgfiles[0]
            print(img.filename)
            print(img.body)
            print(img.content_type)
            # 對檔案進行重新命名
            name = get_file_name_by_time() +img.filename
            #阿里雲檔案上傳            
            status=uploat_file(img.body,name)
            if status==200:
                result = {}
                result["src"] = "http://img1.jiutouxiang.com/"+name
                self.write(str(RJ(data=result)))
                return
        #相當於響應給頁面
        self.write(str(RJ(success=False)))

4.阿里雲上傳檔案程式碼

# -*- coding: utf-8 -*-
import oss2

#上傳檔案到阿里雲
def uploat_file(input,name):
    # 阿里雲主賬號AccessKey擁有所有API的訪問許可權,風險很高。強烈建議您建立並使用RAM賬號進行API訪問或日常運維,請登入 https://ram.console.aliyun.com 建立RAM賬號。
    #auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
    auth = oss2.Auth('51oVyuUmca02rNUe', 'DknGfLtN9Uo1he17CQd1cKtWyhS2Xq')
    # Endpoint以杭州為例,其它Region請按實際情況填寫。
    bucket = oss2.Bucket(auth, 'http://oss-cn-shanghai.aliyuncs.com', 'jiutouxiang-oss')

    # requests.get返回的是一個可迭代物件(Iterable),此時Python SDK會通過Chunked Encoding方式上傳。
    #input = requests.get('http://www.aliyun.com')
    return bucket.put_object(name, input).status