无法在回调函数中调用任何 fineUploader 方法

Can't call any fineUploader methods in callback function

我将 autoUpload 设置为 false,因为我想自己将图像上传到我的后端。但是,为此我首先需要文件对象。在回调 onSubmitted 事件中,我试图将图像 ID 传递给 getFile 方法,传递给 return 对象。但是,当我尝试这样做时,我收到以下错误消息。

in onSubmitted: id=0 | name=28603454_15219061700_r.jpg index.js:2178

[Fine Uploader 5.16.2] Caught exception in 'onSubmitted' callback - Cannot read property 'uploader' of null

我猜我得到这个是因为我声明了一个 const 对象并同时引用它,我相信你不能这样做......

那么,关于如何在 callbacks 函数中调用方法有什么想法吗?或者还有其他方法吗?

const uploader = new FineUploaderTraditional({
  options: {
    maxConnections: 1,
    autoUpload: false,
    deleteFile: { enabled: true, endpoint: "/uploads" },
    request: { endpoint: "/uploads" },
    retry: { enableAuto: true },
    callbacks: {
      onSubmitted: function(id, name) {
        console.log("in onSubmitted: id=" + id + " | name=" + name);
        // getFile(id) returns a `File` or `Blob` object.
        console.log(this.uploader.getFile(id));
      }
    }
  }
});

更新 我现在已经获取了我所有的精细上传器代码并用它创建了一个新组件。我仍然面临同样的问题。组件代码如下:

FineUploader.jsx

import React, { Component } from "react";
import FineUploaderTraditional from "fine-uploader-wrappers";
import Gallery from "react-fine-uploader";
import Filename from "react-fine-uploader/filename";
import "react-fine-uploader/gallery/gallery.css";

const util = require("util");

const uploader = new FineUploaderTraditional({
  options: {
    // debug: true,
    maxConnections: 1,
    autoUpload: false,
    deleteFile: { enabled: true, endpoint: "/uploads" },
    request: { endpoint: "/uploads" },
    retry: { enableAuto: true },
    validation: {
      acceptFiles: ".jpg,.png,.gif,.jpeg",
      allowedExtensions: ["jpg", "png", "gif", "jpeg"],
      itemLimit: 5,
      sizeLimit: 5000000
    },
    callbacks: {
      onCancel: function() {
        console.log("in onCancel: ");
      },
      onComplete: function(id, name, responseJSON, xhr) {
        console.log("in onComplete: " + id + " | " + name + " | " + responseJSON + " | " + xhr);
      },
      onAllComplete: function(succeeded, failed) {
        console.log("in onAllComplete: " + succeeded + " | " + failed);
      },
      onProgress: function(id, name, uploadedBytes, totalBytes) {
        console.log("in onProgress: " + id + " | " + name + " | " + uploadedBytes + " | " + totalBytes);
      },
      onError: function(id, name, errorReason, xhr) {
        console.log("in onError: " + id + " | " + name + " | " + errorReason + " | " + xhr);
      },
      onDelete: function(id) {
        console.log("in onDelete: " + id);
      },
      onDeleteComplete: function(id, xhr, isError) {
        console.log("in onDeleteComplete: " + id + " | " + xhr + " | " + isError);
      },
      onPasteReceived: function(blob) {
        console.log("in onPasteReceived: " + blob);
      },
      onResume: function(id, name, chunkData, customResumeData) {
        console.log("in onResume: " + id + " | " + name + " | " + chunkData + " | " + customResumeData);
      },
      onStatusChange: function(id, oldStatus, newStatus) {
        console.log("in onStatusChange: " + id + " | " + oldStatus + " | " + newStatus);
      },
      onSubmit: function(id, name) {
        console.log("in onSubmit: " + id + " | " + name);
      },
      onSubmitted: function(id, name) {
        console.log("in onSubmitted: id=" + id + " | name=" + name);
        // getFile(id) returns a `File` or `Blob` object.
        // console.log(this.uploader.getFile(id));
        // console.log(uploader.getFile(id));
        // nothing here is working.... :(
      },
      onUpload: function(id, name) {
        console.log("in onUpload: " + id + " | " + name);
      },
      onValidate: function(data, buttonContainer) {
        console.log(
          "in onValidate: " + util.inspect(data, { showHidden: true, depth: null }) + " | " + buttonContainer
        );
      },
      onSessionRequestComplete: function(response, success, xhrOrXdr) {
        console.log("in onSessionRequestComplete: " + response + " | " + success + " | " + xhrOrXdr);
      }
    }
  }
});

const fileInputChildren = <span>Click to Add Photos</span>;
const statusTextOverride = {
  upload_successful: "Success!"
};

class FineUploader extends Component {
  constructor() {
    super();

    this.state = {
      submittedFiles: []
    };
  }

  componentDidMount() {
    uploader.on("submitted", id => {
      const submittedFiles = this.state.submittedFiles;
      console.log("submittedFiles: " + submittedFiles);

      submittedFiles.push(id);
      this.setState({ submittedFiles });
    });
  }

  render() {
    return (
      <div>
        {this.state.submittedFiles.map(id => (
          <Filename id={id} uploader={uploader} />
        ))}
        <Gallery
          fileInput-children={fileInputChildren}
          status-text={{ text: statusTextOverride }}
          uploader={uploader}
        />
      </div>
    );
  }
}

export default FineUploader;

并且 -- 现在在主页上,我正在导入 FineUploader.jsx,并使用该组件。

import FineUploader from "../../components/FineUploader";

在我的渲染方法中我有:

<FineUploader />

this 在 javascript 中很棘手。在常规函数(例如,function f(){...})中,this 取决于函数在哪里 被调用 而不是它被定义的地方。通过第三方 api 使用回调时,您实际上无法控制它的调用位置,因此您最终可能会遇到上述错误。

幸运的是,您可以使用箭头函数(例如 const f = () => {...};)根据函数 定义.[=20= 的位置绑定 this ]

参见MDN docs for more info or you can reference this excellent SO answer

但是,特别是对于您的代码,当您定义 onSubmitted 只是 global/window 对象时,我不确定其中任何一个都可以作为您的 this

为了让它工作,您需要在顶层创建一个闭包(就在您实际创建上传器之前):

function onSubmitted(id, name) {
    console.log("in onSubmitted: id=" + id + " | name=" + name);
    // getFile(id) returns a `File` or `Blob` object.
    console.log(uploader.getFile(id));
}

const uploader = new FineUploaderTraditional({..., callbacks: {onSubmitted, ...}});

这将允许您在实际实例化上传器之前定义与上传器交互的逻辑(这就是您想要的样子)。注意缺少 this,因为我们只是利用 js 闭包规则。

而不是 console.log(this.uploader.getFile(id)); 试试:

console.log(uploader.methods.getFile(id));