Warm tip: This article is reproduced from serverfault.com, please click

How to access response returned by web API after a successful upload?

发布于 2019-04-11 10:39:36

I have checked the documentations but not anywhere I can find any details to the requirement I need.

Here's a web API resource it's called when uploading which returns a json of its filename and content.

    [HttpPost, DisableRequestSizeLimit]
    public ActionResult Upload()
    {
        try
        {
            var stamp = FileHelper.FormatShortDateForfilename(DateTime.Now, true);
            var file = Request.Form.Files[0];
            if (file.Length == 0)
                throw new Exception("No file uploaded.");

            var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
            fileName = $"[{stamp}] {fileName}";
            var fullPath = Path.Combine(webRootPath, fileName);

            var ext = Path.GetExtension(fileName);
            if (!acceptables.Contains(ext.Replace(".", "")))
                throw new Exception($"Only {String.Join("-", acceptables).ToUpper()} files are acceptables.");

            using (var stream = new FileStream(fullPath, FileMode.Create))
            {
                file.CopyTo(stream);
            }

            dynamic upldData = new JObject();
            upldData.filename = fileName;
            upldData.Content = "........";
            return Json(upldData.ToString());
        }
        catch (Exception ex)
        {
            //return Json("Upload Failed: " + ex.Message);
            throw;
        }
    }

And here's from my ReactJS script where I will need to access that response.

<FilePond ref={ref => this.pond = ref}
                server="api/imports"
                labelIdle={'Drag & Drop your CSV file here or <span class="filepond--label-action">Browse</span>'}
                checkValidity={true}
                acceptedFileTypes={['application/vnd.ms-excel']}
                onupdatefiles={fs => {
                    this.setState({ hasFile: fs.length });
                }}
                onremovefile={(fs) => {
                    this.setState({ hasFile: fs && fs.length });
                }}
                onaddfile={fs => { this.setState({ hasFile: false }) }}
                onprocessfile={(err, file) => {
                    console.log('FilePond ready for use', err, file);
                    console.log('test', file.serverId);
                }}
            />
Questioner
JamesCM
Viewed
0
Tigran Keshishyan 2019-04-11 20:18:54

I just spend some time to figure out what is going on here. This is the main functionality for creating requests inside filePond.

const createProcessorFunction = (apiUrl = '', action, name) => {
  // custom handler (should also handle file, load, error, progress and abort)
  if (typeof action === 'function') {
    return (...params) => action(name, ...params);
  }

  // no action supplied
  if (!action || !isString(action.url)) {
    return null;
  }

  // internal handler
  return (file, metadata, load, error, progress, abort) => {
    // set onload hanlder
    const ondata = action.ondata || (fd => fd);
    const onload = action.onload || (res => res);
    const onerror = action.onerror || (res => null);

    // no file received
    if (!file) return;

    // create formdata object
    var formData = new FormData();

    // add metadata under same name
    if (isObject(metadata)) {
      formData.append(name, JSON.stringify(metadata));
    }

    // Turn into an array of objects so no matter what the input, we can handle it the same way
    (file instanceof Blob ? [{ name: null, file }] : file).forEach(item => {
      formData.append(
        name,
        item.file,
        item.name === null ? item.file.name : `${item.name}${item.file.name}`
      );
    });

    // send request object
    const request = sendRequest(ondata(formData), apiUrl + action.url, action);
    request.onload = xhr => {
      load(
        createResponse(
          'load',
          xhr.status,
          onload(xhr.response),
          xhr.getAllResponseHeaders()
        )
      );
    };

    request.onerror = xhr => {
      error(
        createResponse(
          'error',
          xhr.status,
          onerror(xhr.response) || xhr.statusText,
          xhr.getAllResponseHeaders()
        )
      );
    };

    request.ontimeout = createTimeoutResponse(error);
    request.onprogress = progress;
    request.onabort = abort;

    // should return request
    return request;
  };
};

As you see You can pass a function or an object as a value for server property. There are some methods like onload, onerror and ondata which you can check and try to find the solution for your issue. Or just pass custom function and do your request inside of it like

<FilePond server={(...args) => this.handleUploadRequest(...args)} />

I hope it will help you. Thanks