如何解决在上传图像过程中向服务器发送附加信息
我在 vue 2.6.11 上使用 filepond 4.25.1,到目前为止一切正常。 我想向我的 aspnet core 3 服务器发送附加信息。我从 filepond 发送我的请求,如下所示
myServer: {
url: "http://**********/api/CustomerAuth/",process: {
url: "uploadimages",method: "POST",withCredentials: false,headers: {},data: {
nationalcode: "1234567890",typecode:"1"
},timeout: 7000,},load: (source,load) => {
fetch(source)
.then((res) => res.blob())
.then(load);
},}
和服务器端
[HttpPost("uploadimages")]
public IActionResult UploadImages()
{
try
{
var file = Request.Form.Files[0];
string folderName = "Upload";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath,folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string fileName =
ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
string fullPath = Path.Combine(newPath,fileName);
using (var stream = new FileStream(fullPath,FileMode.Create))
{
file.CopyTo(stream);
}
}
return Ok("Upload Successful");
}
catch (System.Exception ex)
{
return NotFound(new { img_upld_error = ex.Message });
}
}
在服务器端,我需要访问作为数据发送的“nationalcode”和“typecode”,这两个参数的值总是在变化,因此它不是静态值,并且这两个参数的用户值的交互总是变化。
如果有人给我一些线索或指导我解决我的问题,我真的很感激。
解决方法
此处为 FilePond 开发人员。
data
不作为 process
上的道具存在。
您可以使用 ondata
属性添加额外的 FormData 参数。请参阅下面的更新示例:
myServer: {
url: "http://**********/api/CustomerAuth/",process: {
url: "uploadimages",method: "POST",withCredentials: false,headers: {},data: {
nationalcode: "1234567890",typecode:"1"
},ondata: (formData) => {
formData.append('nationalcode','1234567890');
formData.append('typecode','1');
return formData;
}
timeout: 7000,},load: (source,load) => {
fetch(source)
.then((res) => res.blob())
.then(load);
},}
或者,您可以使用 filepond 元数据插件向每个文件添加元数据(这会自动发送到服务器)。 https://pqina.nl/filepond/docs/patterns/plugins/file-metadata/
FilePond.setOptions({
fileMetadataObject: {
'nationalcode': '1234567890','typecode': '1'
}
})
,
你可以在模型中获取文件,像这样定义你的模型
public class FileWithDataModel
{
public IFormFile File { get; set; }
public string NationalCode { get; set; }
public string TypeCode { get; set; }
}
和控制器方法将是:
public async Task<IActionResult> UploadFileWithData(FileWithDataModel model)
{
var file = model.File;
//you can save this file...
var nCode = model.NationalCode; //can access data easy
//......
return Ok();
}
Microsoft 建议使用 Async 方法,尤其是文件处理和上传
这里是jquery客户端的例子
var form = new FormData();
form.append("NationalCode","12345678");
form.append("TypeCode","1");
form.append("File",fileInput.files[0],"/path/to/file");
var settings = {
"url": "http://**********/api/CustomerAuth/","method": "POST","timeout": 0,"headers": {
"Content-Type": "application/x-www-form-urlencoded"
},"processData": false,"mimeType": "multipart/form-data","contentType": false,"data": form
};
$.ajax(settings).done(function (response) {
console.log(response);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。