首页 > 解决方案 > 上传成功后如何访问 Web API 返回的响应?

问题描述

我已经检查了文档,但在任何地方都找不到我需要的任何详细信息。

这是上传时调用的 Web API 资源,它返回其文件名和内容的 json。

    [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;
        }
    }

这是我的 ReactJS 脚本,我需要在其中访问该响应。

<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);
                }}
            />

标签: reactjsasp.net-web-apifilepond

解决方案


您可以在回调中访问响应server.process.onload,确保您仍然在所述回调中返回唯一的文件 ID。

自定义处理方法也可以使用,您可以在此处找到更多信息: https ://pqina.nl/filepond/docs/patterns/api/server/#advanced


推荐阅读