[英]C# IFormFile wrapper interface
我觉得这是一件很容易做的事情,但由于某种原因,在我的代码中,我得到了 null 值。
前端为 Angular,后端为 C# .NET。
我正在发帖上传formData。 提交表单并进行 POST 以将图像上传到 blob 容器时,我的问题正在发生。
当用户上传照片并提交表单时,照片将转换为 base64 图像。 并且在 imageFile 中添加了一个自定义属性:
这是帖子数据:
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 。 但在后端,POST 仅在参数中的类型设置为ICollection<IFormFile>时有效
[HttpPost]
public async Task<ActionResult<IEnumerable<T>>> UploadPhotos([FromRoute] Guid Id, ICollection<IFormFile> files, CancellationToken cancellationToken = default){}
然后将在帖子的文件参数中获得以下内容:
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; }
}
但它会在帖子的文件参数中给我null 。 所以它击中了帖子,但没有填充任何属性。
到目前为止,我已经尝试过:
他们都打了post方法,但给了我null。
我理解 inheritance 错了吗? 或者它是如何从表单中反序列化内容的?
我没有制作自定义活页夹,而是将 isThumbnail 数组传递到 FormData javascript object 中。 它像字典一样工作。 因此,当我创建实体时,我可以将它用于 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.