我觉得这是一件很容易做到的事情,但出于某种原因,在我的代码中,我得到了一个空值。
前端是角的,后端是C# .NET.
我正在做一个帖子上传formData。当表单被提交时,我的问题就发生了,我发了一篇文章将图片上传到blob容器。
当用户上传照片并提交表单时,照片将转换为base64图像。并且在imageFile中添加了一个自定义属性:
这是post数据
File{
isThumbnail: false,
name: "Forest-Village.jpg",
lastModified: 1638304459833,
size: 205605,
type: "image/jpeg",
lastModifiedDate: Tue Nov 30 2021 15:34:19 GMT-0500 (Eastern Standard Time) {},
webkitRelativePath: ""
}我想在后端使用isThumbnail。但是在后端,只有当参数中的类型设置为ICollection时,POST才能工作。
[HttpPost]
public async Task<ActionResult<IEnumerable<T>>> UploadPhotos([FromRoute] Guid Id, ICollection<IFormFile> files, CancellationToken cancellationToken = default){}然后,它将在post的文件参数中获得以下内容:
ContentDisposition: form-data; name="files"; filename="Forest-Village.jpg"
ContentType: "image/jpeg"
FileName: Forest-Village.jpg
Headers:{Microsoft.AspNetCore.Http.HeaderDictionary}
Length: 205605
Name: "files"因此,我缺少了isThumbnail属性。
IFormFile接口包含以下方法和属性以供参考:
namespace Microsoft.AspNetCore.Http
{
// Summary:
// Represents a file sent with the HttpRequest.
public interface IFormFile
{
string ContentType { get; }
string ContentDisposition { get; }
IHeaderDictionary Headers { get; }
long Length { get; }
string Name { get; }
string FileName { get; }
void CopyTo(Stream target);
Task CopyToAsync(Stream target, CancellationToken cancellationToken = default);
Stream OpenReadStream();
}
}因此,我创建了这个IFormFileWrapper接口,并将它放在httpPost参数中:
[HttpPost]
public async Task<ActionResult<IEnumerable<T>>> UploadPhotos([FromRoute] Guid Id, ICollection<IFormFileWrapper> files, CancellationToken cancellationToken = default){}public interface IFormFileWrapper : IFormFile
{
bool IsThumbnail { get; }
}但是它将在post的文件参数中给出null。因此,它会击中post,但没有填充任何属性。
到目前为止,我已经尝试过:
在继承IFormFile
的所有属性
他们都击中了post方法,但给了我null。
我对遗产的理解错了吗?或者它是如何从表单中反序列化内容的?
发布于 2022-01-02 16:43:23
我没有制作自定义绑定器,而是将isThumbnail数组传递给FormData javascript对象。它就像一本字典。所以当我创建一个实体时,我可以用它来对付IFormFiles。
if (!!uploadedPhotos && uploadedPhotos.length > 0) {
let thumbnailValues = uploadedPhotos.map(p => p.isThumbnail)
let uploadedFiles = uploadedPhotos.map(p => p.file);
let formData = new FormData();
uploadedFiles.forEach((f, index) => {
formData.append("files", f);
formData.append("isthumbnail", String(thumbnailValues[index]));
});
newImgs$ = this._imageService.postImages(this.Id, formData);所以在后端,我要做的就是:
var request = await Request.ReadFormAsync();
var isthumbnail = request["isthumbnail"];https://stackoverflow.com/questions/70546300
复制相似问题