使用拖放区将文件直接上传到 Azure Blob 存储(使用 SAS).js

Upload file directly to Azure Blob Storage (with SAS) using dropzone.js

本文关键字:存储 Blob Azure 使用 js SAS 拖放区 文件      更新时间:2023-09-26

我想使用dropzone.js将文件直接上传到Azure Blob存储,并使用SAS(此处的示例)将文件保密。

据我了解,工作流程将是:

  1. 用户选择一个文件
  2. 放置区processing事件将触发。在事件处理程序中,我在站点的 API 上调用一个方法,该方法创建要上传到的 Azure Blob URI,包括 SAS 查询字符串
  3. 拖放区上传 URL 设置为"安全"blob URL
  4. 上传开始

我找到了以下维基文章,展示了如何动态设置拖放区 URL(https://github.com/enyo/dropzone/wiki/Set-URL-dynamically)

Dropzone.options.myDropzone = {
  init: function() {
    this.on("processing", function(file) {
      // I need to do an async call here, to get the URL...
      this.options.url = "/some-other-url";
    });
  }
};

问题是上面的例子是同步的。如何延迟上传,直到从我的 Web API 异步请求 URL?

谢谢

可能是我回答得有点晚了

使用预定义的 SAS

只需在呈现页面时将其保存在具有data-sas属性form元素中即可。我看到的唯一缺点 - 如果页面有一段时间没有刷新,您的 SAS 可能会过期。这是我的工作代码的一部分(其他变体来自我的头脑)

Dropzone.options.myDropzone = {
  method: "PUT",
  headers: {"x-ms-blob-type": "BlockBlob"},
  sending: (file, xhr) => {
    // To send file without wrappintng it to multipart/form-data,
    // Azure won’t unwrap it
    const _send = xhr.send;
    xhr.send = () => { _send.call(xhr, file) };
  },
  init: function() {
    const dz = this,
          action = dz.element.action,
          sas = dz.element.dataset.sas;
    dz.on("processing", (file) => {
      dz.options.headers["Content-Type"] = file.type;
      dz.options.url = `${action}/${file.name}?${sas}`;
    })
  },
}

在Dropzone的init中使用异步调用

Dropzone.options.myDropzone = {
  autoProcessQueue: false, // To prevent automatic auploading before getting SAS
  acceptedFiles: ".xls,.xlsx",
  method: "PUT",
  headers: {"x-ms-blob-type": "BlockBlob"},
  sending: (file, xhr) => {
    // To send file without wrappintng it to multipart/form-data,
    // Azure won’t unwrap it
    const _send = xhr.send;
    xhr.send = () => { _send.call(xhr, file) };
  },
  init: function() {
    let sas = null;
    const dz = this,
          xhr = new XMLHttpRequest();
    xhr.addEventListener("load",
        (event) => {
          sas = getSasFromEvent(event);
          dz.options.autoProcessQueue = true;
          dz.processQueue();
        }, true);
    xhr.open("GET", "/get-sas");
    xhr.send();
    dz.on("processing", (file) => {
      dz.options.headers["Content-Type"] = file.type;
      dz.options.url = `${action}/${file.name}?${sas}`;
    })
  },
}

获得 SAS 异步后运行 Dropzone

请参阅以编程方式创建放置区

你可以尝试使用 jQuery 进行同步 ajax 调用。

function GetUrl() {
    var url = "";
    $.ajax({
        async: false,
        success: function(data) {
            url = data;
        }
        // Other opts   
    });
    return url;
}
Dropzone.options.myDropzone = {
  init: function() {
    this.on("processing", function(file) {
      this.options.url = GetUrl();
    });
  }
};