【问题标题】:How to keep the original filename in React when fetched from Django?从 Django 获取时如何在 React 中保留原始文件名?
【发布时间】:2022-06-30 17:51:35
【问题描述】:

我正在使用 Django-Graphene-React 堆栈,在我的前端,用户必须能够从后端下载文件。

效果很好。

但是,文件名是在后端定义的,并通过 Django 发送的 HttpRequest 中的 Content-Disposition 标头发送。但是当我在前端获取它时,我无法检索它。

这是生成文件的后端 Django 视图:

import io

from django.http import HttpResponse


def download_file_view(request):
    buffer = io.BytesIO()
    # Generate an Excel file and put it a buffer...
    ...
    buffer.seek(0)
 
    response = HttpResponse(
        buffer.read(),
        content_type="application/vnd.openxmlformats-officedocument"
                     ".spreadsheetml.sheet",
    )

    # The filename is generated in the backend (Django) and cannot be
    # generated from the frontend (React)
    response["Content-Disposition"] = "filename.xlsx"

    return response

如果我通过在浏览器中输入分配给此视图的 url 直接下载它,当我的浏览器提示我保存文件时,我会正确获取文件名。

但是,我想在前端获取文件,以便在后端生成文件期间获得加载状态。

这是我在 React 中的前端组件:

import {useState) from "react";


const DownloadButton = ({downloadUrl}) => {
  const [isLoading, setIsLoading] = useState(false);

  const fetchExport = async() => {
    try {
      setIsLoading(true);
      const response = await fetch(downloadUrl);

      const header = response.headers.get("Content-Disposition");  // Empty
      console.log(response);  // Headers are empty

      const blob = await response.blob();

      let objectUrl = window.URL.createObjectURL(blob);
      let link = document.createElement("a");
      link.href = objectUrl;

      // By the way, these two lines clears my console and sometimes my
      // development server stops, I don't know why yet.
      link.click(); 
      link.remove(); 

    } catch (error) {
      console.log(error);
    } finally {
      setIsLoading(false);
    }
  }

  if (isLoading){
    return <div>Loading...</div>
  } else {
    return <div onClick={fetchExport}>Download</div>
}

所以我得到了文件。这工作正常。但不是原始文件名,而是我的前端 url 和一些随机 uuid 作为文件名。

【问题讨论】:

    标签: reactjs django fetch response-headers


    【解决方案1】:

    我需要在 django 设置中添加这个(使用 corsheaders)。

    CORS_EXPOSE_HEADERS = ['Content-Disposition']
    

    【讨论】:

      猜你喜欢
      • 2014-12-30
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 2020-02-16
      • 2014-06-20
      • 2014-12-07
      • 2011-03-30
      相关资源
      最近更新 更多