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

时间:2018-08-28 13:07:07

标签: javascript reactjs callback fine-uploader

我将autoUpload设置为false,因为我想将图像自己上传到后端。但是,要做到这一点,我首先需要文件对象。在回调onSubmitted事件中,我试图将图像id传递给getFile方法,以返回对象。但是,当我尝试执行此操作时,出现以下错误消息。

  

在onSubmitted中:id = 0 |名称= 28603454_15219061700_r.jpg index.js:2178

     

[Fine Uploader 5.16.2]在“ onSubmitted”回调中捕获了异常-   无法读取null的属性“ uploader”

我猜我明白了,因为我声明了一个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 />

2 个答案:

答案 0 :(得分:3)

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

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

有关更多信息,请参见MDN docs。您也可以参考this excellent SO answer

但是,特别是对于您的代码,当您定义this只是全局/窗口对象时,我不确定它们中的哪一个都可以作为您的onSubmitted

要使其正常工作,您需要在顶层创建一个闭包(在实际创建上传器之前):

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, ...}});

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

答案 1 :(得分:0)

代替public class SubSetSum { boolean[][] solution; int[] input; int k; public SubSetSum(int[] input, int targetSum) { this.input = input; this.k = targetSum; this.solution = new boolean[input.length+1][k+1]; } public boolean subsetSum() { int n = input.length; for (int i = 0; i <= n; i++) { //case 1 solution[i][0] = true; } for (int j = 0; j <= k; j++) { // case 2 solution[0][j] = false; } for (int i = 1; i <= n; i++) { // n times for (int j = 1; j <= k; j++) { // k times and time complexity O(n*k) if(solution[i-1][j]) { solution[i][j] = solution[i-1][j]; // case 3 continue; } if(j >= input[i-1]) { // case 4 solution[i][j] = solution[i-1][j-input[i-1]]; } } } return solution[n][k]; } } 试试:

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