亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Django+Vue實現(xiàn)文件上傳下載的項目實踐

 更新時間:2023年06月07日 11:27:26   作者:穿越寒冬  
本文主要介紹了Django+Vue實現(xiàn)文件上傳下載的項目實踐,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

前言

首先我要實現(xiàn)的頁面效果是這樣的

 當點擊上傳文件按鈕,彈出上傳文件的彈出框,可以上傳多個文件,點擊確定后才正式開始上傳

 點擊右側(cè)下載按鈕,可以直接下載文件。

上傳功能

后端代碼

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, '../upload')
MEDIA_URL = '/upload/'

這段代碼表示你上傳的文件都會放在你項目根目錄的upload文件夾下。

views.py

@api_view(('POST',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def upload_list(request):
    # 如果項目根目錄沒有upload文件夾,會自動給你創(chuàng)建一個
    folder_path = settings.MEDIA_ROOT
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    files = request.FILES.getlist('file')
    for file in files:
        # 這三行代碼就是上傳文件的代碼
        f = open(settings.MEDIA_ROOT + "/" + file.name, mode='wb')
        for chunk in file.chunks():
            f.write(chunk)
        # 這段代碼是我要網(wǎng)數(shù)據(jù)庫里存的一些文件信息,如果不存庫的話不用寫
        size = file.size
        suffix = file.content_type
        createUser = request.user
        filePath = settings.MEDIA_URL + file.name
        name = file.name
        # 上傳完文件記得要關(guān)閉
        # 需要注意的一點,如果f.close()這句代碼之前,上傳文件之后有報錯,那你文件是一直被占用的狀態(tài),刪除也刪不掉,所以一定要做好代碼順序
        f.close()
        # 往數(shù)據(jù)庫里存文件信息
        Filemanage.objects.create(size=size, suffix=suffix, create_user=createUser, file_path=filePath, name=name)
    return JsonResponse(OrderedDict([
        ('results', {})
    ], code=status.HTTP_200_OK))

前端代碼

<el-upload
          class="upload-demo"
          ref="upload"
          action=""
          :auto-upload="false"
          :http-request="upload"
          :before-upload="beforeAvatarUpload"
          multiple
        >
          <el-button size="small" type="primary">點擊上傳</el-button>
        </el-upload>

:ref="upload":必須要寫,因為我們是手動上傳方式。

:auto-upload="false":這里我設(shè)置的不自動上傳,如果你沒有確定按鈕,點擊一起上傳的需求,那你就把值變?yōu)閠ure,你選完文件后會自動上傳。

:http-request="upload":覆蓋默認的上傳行為,可以自定義上傳的實現(xiàn)。

:before-upload="beforeAvatarUpload":上傳文件之前的鉤子,一般用于限制上傳文件大小和類型。

multiple:多文件上傳。

methods: {
    beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 200;
        if (!isLt2M) {
            this.$message.error('上傳頭像圖片大小不能超過2MB!');
        }
        return isLt2M;
    },
    upload(param) {
        const formData = new FormData()
        formData.append('file', param.file)
        mail.uploadFile(formData).then(response => {
            console.log('上傳圖片成功')
            this.$refs.upload.clearFiles()
        }).catch(response => {
            console.log(response)
            this.$refs.upload.clearFiles()
        });
    },
}

下載功能

后端代碼

def download(request, nid):
    # 通過前臺傳來的id查出文件名
    row_object = Filemanage.objects.filter(id=nid).first()
    # 文件的相對路徑
    file_path = '/upload/' + row_object.name
    # 打開文件
    with open(settings.MEDIA_ROOT + "/" + row_object.name, 'rb') as f:
        response = HttpResponse(f.read())
    # 設(shè)置Content-Disposition頭以強制瀏覽器下載文件
    file_name = os.path.basename(file_path)
    response["Content-Type"] = "application/octet-stream"
    response['Content-Disposition'] = f'attachment; filename="{file_name}"'
    return response

前端代碼

<el-button
  v-if="permissionList.del"
  size="small"
  type="success "
  @click="download(row)"
>{{ "下載" }}</el-button>
methods: {
    download(row) {
	    this.loading = true;
        // 這塊是我封裝的axios請求,請求時要帶著responseType: 'blob',我會在下面放上我的代碼
	    file.requestDownload(row.id).then((response) => {
	      const url = window.URL.createObjectURL(new Blob([response.data]));
	      const link = document.createElement('a');
	      link.href = url;
	      link.setAttribute('download', row.name);
	      document.body.appendChild(link);
	      link.click();
	    })
	    .catch((e) => {
	      console.log(e)
	    });
    },
}
requestDownload(id) {
    return request({
      url: '/tool/download/' + id + '/',
      method: 'get',
      responseType: 'blob'
    })
}

 到此這篇關(guān)于Django+Vue實現(xiàn)文件上傳下載的項目實踐的文章就介紹到這了,更多相關(guān)Django Vue文件上傳下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論