IFormFile的文件路径在哪里?

김세림*_*김세림 4 asp.net-web-api asp.net-core

当我从 C# 接收到 iformfile 的文件时,我如何知道该文件的文件路径?如果我不知道,我该如何设置路径?

public async Task<JObject> files(IFormFile files){
string filePath = "";
var fileStream = System.IO.File.OpenRead(filePath)
}
Run Code Online (Sandbox Code Playgroud)

小智 8

本文档中,介绍了一些说明IFormFile

使用 IFormFile 技术上传的文件在处理之前会缓冲在服务器的内存或磁盘中。在操作方法内,IFormFile 内容可以作为 Stream 进行访问。

所以对于IFormFile,需要先保存到本地,然后再使用本地路径。

例如:

// Uses Path.GetTempFileName to return a full path for a file, including the file name.
var filePath = Path.GetTempFileName();

using (var stream = System.IO.File.Create(filePath))
{
    // The formFile is the method parameter which type is IFormFile
    // Saves the files to the local file system using a file name generated by the app.
    await formFile.CopyToAsync(stream);
}
Run Code Online (Sandbox Code Playgroud)

之后就可以获取本地文件路径,即filePath.