读取 HTTP 文件和表单数据,而无需使用 Web API 写入磁盘



我的问题与此类似: webapi-file-uploading-without-write-files-to-disk

但是,这个问题和大多数其他类似问题都止步于读取文件数据。我已经使该位正常工作,但我也想读取表单中的其余表单数据,该表单具有其他上传元素,例如"标题"等。这来自上述问题中的解决方案:

var filesToReadProvider = await Request.Content.ReadAsMultipartAsync();

filesToReadProvider是HTTPContent对象的集合,所以我尝试了:

List<HttpContent> uploadedstuff = filesToReadProvider.Contents.ToList();
Image image = new Image(); ;        // The image object we will create
Stream filestream;  // The file stream object to use with the image
foreach (var thing in uploadedstuff)
{
try
{
string name = thing.Headers.ContentDisposition.Name.Replace(""", ""); // String is quoted """namestring""" so need it stripped out
List<NameValueHeaderValue> parameters = thing.Headers.ContentDisposition.Parameters.ToList();
if (name == "file")
{
image.LocalFileName = thing.Headers.ContentDisposition.FileName;
filestream = await thing.ReadAsStreamAsync();
}
if (name == "Title")
{
// vvv- this line causes an exception.
NameValueCollection titleData = await thing.ReadAsFormDataAsync();
}
}
catch (System.Exception e)
{
var message = "Something went wrong";
HttpResponseMessage err = new HttpResponseMessage() { StatusCode = HttpStatusCode.ExpectationFailed, ReasonPhrase = message };
return ResponseMessage(err);
}
}

任何想法我应该做什么才能获得例如:"标题"表单数据?我觉得我很接近,但可能采取了错误的方法? 非常感谢。

现在它在评论中得到了整理,我将发布这个答案来帮助其他人。

表单多部分内容像这样将数据发送回服务器">

---------------------------acebdf13572468
Content-Disposition: form-data; name="file"; 
Content-Type: image/*
<@INCLUDE *App.jpg*@>
---------------------------acebdf13572468
Content-Disposition: form-data; name="TextField";
Content-Type: application/octet-stream
Text Value
---------------------------acebdf13572468
Content-Disposition: form-data; name="JsonField";
Content-Type: application/json
{
"Json" : "Object"
}
---------------------------acebdf13572468--

用分隔线分隔的每个部分(即---------------------------acebdf13572468(是它自己的内容,因此是多部分的。

您可以在一个字段中以 json 形式发送数据,如上所示,也可以发送文本或任何内容。通常,浏览器将每个控件发送到其自己的单个部分中。可以通过模型绑定器读取此类数据 ASP.Net 方法是在控制器参数中指定[FromForm]

或者,在这种特殊情况下,您可能会thing.ReadAsStreamAsync();thing.ReadAsStringAsync();

--编辑--

因此,上述方法在直接读取数据或不是 MVC 项目时很有用。如果您使用的是MVC,则可以轻松阅读以下内容。

假设你有一个这样的模型

public class Model
{
public string Title { get; set; }
}

然后,您将创建一个控制器和操作,如下所示:

public class MainController : Controller
{
[HttpPost]
public async Task<IActionResult> UploadImage([FromForm]Model model)
{
var files = Request.Files;
var title = model.Title
//And you can save or use files and content at the same time.
}
}

这通常是您在 MVC 场景中执行的操作,如果您在客户端使用 Razor 或 Pages,您甚至不需要指定 [FromForm] 属性。

我希望这对你有所帮助。

免責聲明。我已经在浏览器中编写了所有这些。可能包含语法和其他错误。

最新更新