Angular和Web API核心之间的图像传输



从3天起,我一直在尝试在Angular和Web api核心之间进行图像传输,反之亦然,但我无法做到。我在互联网上搜索了很多,但没有找到任何Web api核心的例子。

如果有人能给我提供文档/示例或一些教程的链接,我将非常感谢。

现在我正在通过Json对象在Angular和API之间进行数据传输。如何将图像转换为json进行传输?

对不起,如果这是一个基本的问题,因为我是新手。

为什么要将图像转换为JSON?

您将文件直接传输到服务。这就是想法。控制器接收POST 提交的文件

后端

using System.Net.Http.Headers;
[HttpPost]
public ActionResult UploadFile()
{
try
{
var file = Request.Form.Files[0];
if (file.Length > 0)
{
string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName;
string fullPath = Path.Combine(@"C:wwwrootupload", fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
}
return Json("OK");
}
catch (System.Exception ex)
{
return Json("Failed");
}
}

前端

export class UploadComponent {
constructor(private http: HttpClient) { }
upload(files) {
if (files.length === 0)
return;
const formData = new FormData();
for (let file of files)
formData.append(file.name, file);
const uploadReq = new HttpRequest('POST', `api/uploadFile`, formData);
this.http.request(uploadReq).subscribe(event => {
if (event.type === HttpEventType.Response)
//DONE
});
}
}

HTML

<input #file type="file" (change)="upload(file.files)" />

最新更新