上传成功后,如何访问web API 返回的响应?
How to access response returned by web API after a successful upload?
我已经检查了文档,但找不到我需要的任何详细信息。
这是一个网络 API 资源,它在上传时调用 returns 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);
}}
/>
您可以在 server.process.onload
回调中访问响应,确保您仍然 return 所述回调中的唯一文件 ID。
自定义处理方法也可以,您可以在此处找到更多信息:
https://pqina.nl/filepond/docs/patterns/api/server/#advanced
我只是花了一些时间弄清楚这里发生了什么。
这是在 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;
};
};
如您所见,您可以将函数或对象作为 server
属性 的值传递。
有一些方法,如 onload
、onerror
和 ondata
,您可以检查并尝试找到解决问题的方法。或者只是传递自定义函数并在其中执行您的请求,例如
<FilePond server={(...args) => this.handleUploadRequest(...args)} />
希望对您有所帮助。谢谢
这就是我在 angular
中所做的
pondOptions = {
class: 'my-filepond',
multiple: true,
labelIdle: 'Drop files here or click to upload',
acceptedFileTypes: 'image/jpeg, image/png',
server: {
url: environment.base_url + environment.upload_file_url,
process: {
headers: {
Authorization: 'Token ' + window.localStorage.getItem('USER_TOKEN') || null
},
onload: (response) => {this.UPLOAD_FILES.push(response)}, // saving response in global array
}
}
};
我已经检查了文档,但找不到我需要的任何详细信息。
这是一个网络 API 资源,它在上传时调用 returns 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);
}}
/>
您可以在 server.process.onload
回调中访问响应,确保您仍然 return 所述回调中的唯一文件 ID。
自定义处理方法也可以,您可以在此处找到更多信息: https://pqina.nl/filepond/docs/patterns/api/server/#advanced
我只是花了一些时间弄清楚这里发生了什么。 这是在 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;
};
};
如您所见,您可以将函数或对象作为 server
属性 的值传递。
有一些方法,如 onload
、onerror
和 ondata
,您可以检查并尝试找到解决问题的方法。或者只是传递自定义函数并在其中执行您的请求,例如
<FilePond server={(...args) => this.handleUploadRequest(...args)} />
希望对您有所帮助。谢谢
这就是我在 angular
中所做的pondOptions = {
class: 'my-filepond',
multiple: true,
labelIdle: 'Drop files here or click to upload',
acceptedFileTypes: 'image/jpeg, image/png',
server: {
url: environment.base_url + environment.upload_file_url,
process: {
headers: {
Authorization: 'Token ' + window.localStorage.getItem('USER_TOKEN') || null
},
onload: (response) => {this.UPLOAD_FILES.push(response)}, // saving response in global array
}
}
};