gpt4 book ai didi

c# - 使用 ng-file 的 AngularJS HTTP POST

转载 作者:行者123 更新时间:2023-11-30 17:37:32 26 4
gpt4 key购买 nike

我似乎无法使用 ng-file upload 进行此操作。我需要在我的 Controller 中使用网桥 ID 传递罚款

我得到的错误是:

"{"Message":"No HTTP resource was found that matches the request URI 
'http://localhost/api/BridgeController/'.","MessageDetail":"No type was
found that matches the controller named 'BridgeController'."}"

无法弄清楚为什么它找不到我的方法。有什么想法吗?

这是我的 Controller 代码,将被移动到服务中

$scope.uploadFile = function (file) {
console.log("hitting file upload", $scope.selectedBridge);
if (file) {
debugger;

var request = {
method: 'POST',
url: '/api/Bridge/UploadBridgeImage',
data: angular.toJson($scope.selectedBridge.BridgeID),
file: file,
headers: { 'Content-Type': undefined }
};

Upload.upload(request).then(function (response) {

});
}
}

和后端 C#

[HttpPost]
[Route("api/Bridge/UploadBridgeImage")]
public IHttpActionResult UploadBridgeImage()
{
try
{
var uploadedFiles = HttpContext.Current.Request.Files;

for (int i = 0; i < uploadedFiles.Count; i++)
{
var fileToSave = uploadedFiles[i];

var fileBytes = _iStremHelper.GetBytes(fileToSave.InputStream, fileToSave.ContentLength);
var file = BridgeFileEntity(fileBytes, fileToSave, 1);

using (_iFileRepository)
{
_iFileRepository.Save(file);
}
}
return Ok();
}
catch (Exception ex)
{
return InternalServerError();
}
}

在此处编辑代码。我能够在我的 C# Controller 中的那个 post 方法中达到我的断点。文件有我需要的所有数据。现在我需要以某种方式获取“数据”。知道它在上下文中的位置吗?

最佳答案

为了在 web api Controller 中获取文件流(在内存中)和额外的 json 数据,您可以定义自定义 MultipartStreamProvider:

class MultipartFormDataInMemoryStreamProvider : MultipartFormDataRemoteStreamProvider
{
public override RemoteStreamInfo GetRemoteStream(HttpContent parent, HttpContentHeaders headers)
{
return new RemoteStreamInfo(new MemoryStream(), string.Empty, string.Empty);
}
}

然后在 Controller 中使用它:

public async Task<IHttpActionResult> UploadBridgeImage()
{
var provider = await Request.Content.ReadAsMultipartAsync(new MultipartFormDataInMemoryStreamProvider());
foreach (var httpContent in provider.Contents)
{
if (!string.IsNullOrEmpty(httpContent.Headers.ContentDisposition?.FileName))
{
var byteArray = await httpContent.ReadAsByteArrayAsync();
//do whatever you need with byteArray
}
}

var bridgeId = provider.FormData["bridgeId"];

return Ok();
}

在客户端:

var request = {
url: '/api/Bridge/UploadBridgeImage',
data: {
file:file,
bridgeId:$scope.selectedBridge.BridgeID
}
};

Upload.upload(request).then(function (response) {

});

关于c# - 使用 ng-file 的 AngularJS HTTP POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37914170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com