Asp.net core 2.0 如何从JObject获取文件值?
我正在使用最新的.net内核,我有mvc应用程序和web Api应用程序,因此mvc应用程序接受请求,所有数据库操作都由web Api应用程序完成,我在上传图像时,大部分时间都与IFormFile相关,因此我设法获取图像数据并绑定到ViewModel。然而,当我将ViewModel作为PostAsJsonAsync传递给web api控制器时,该控制器的参数是ViewModel,它不起作用,因此我改为JObject,现在的问题是如何从中提取IFormFile属性JObject作为IFormFile,我面临InvalidCastException错误。这是我的密码Asp.net core 2.0 如何从JObject获取文件值?,asp.net-core-2.0,asp.net-core-webapi,jobjectformatter,Asp.net Core 2.0,Asp.net Core Webapi,Jobjectformatter,我正在使用最新的.net内核,我有mvc应用程序和web Api应用程序,因此mvc应用程序接受请求,所有数据库操作都由web Api应用程序完成,我在上传图像时,大部分时间都与IFormFile相关,因此我设法获取图像数据并绑定到ViewModel。然而,当我将ViewModel作为PostAsJsonAsync传递给web api控制器时,该控制器的参数是ViewModel,它不起作用,因此我改为JObject,现在的问题是如何从中提取IFormFile属性JObject作为IFormFil
//HTML File
<div class="control-label col-md-2">
@Html.Label("Image")
</div>
<div class="col-md-3 imgdrop">
<input type="file" id="file" name="file"class="form-control-file" />
<div class="img-wrap ">
<span class="close">×</span>
<img src="..." alt="..." id="imgInp" class="img-fluid" />
</div>
</div>
$("#SaveDetailsId").on("click", function () {
var formdata = new FormData();
var table = $("#ItemListTable").DataTable();
$.each(tableData, function (index, item) {
name = 'ItemList[' + index + '].SkuList'; // construct the name
value = item[0];
});
formdata.append("ImageFile", jQuery("#file").get(0).files[0]);
$.ajax({
//headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/json'
//},
url: "/Test/Test",
type: "POST",
data: formdata,
contentType: false,
processData: false,
success: function (response) {
...
});
});
//ViewModel
public class Test
{
public IFormFile ImageFile {get;set;}
.
.
.
}
//MVC Controller
[HttpPost]
public async Task<IActionResult> BuyerCreative([FromForm]Test _viewModel)
{
_viewModel.Ad = _viewModel.Ad;
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await client.PostAsJsonAsync("api/Test/Test", _viewModel);
if (Res.IsSuccessStatusCode)
{
}
//returning the employee list to view
return View(_viewModel);
}
}
//Let me know if there is a way to bind ViewModel instead of JObject
//WEbApi
[Route("api/Test/Test/")]
[HttpPost]
public IActionResult Test([FromBody] JObject data)
{
try
{
_Repository.AddDetails(data);
return Ok();
}
catch (Exception pException)
{
return BadRequest(pException.Message);
}
}
//And Lastly my repository
public void AddDetails(JObject data)
{
DBContext.Items _items = new DBContext.Items();
_items.Number = Convert.ToInt32(((JValue)data.GetValue("Number")).Value);
// I 'm stuck over here, how to get the IFormFile, I tried various options
IFormFile file = (IFormFile)((JValue)data.GetValue("ImageFile"));
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString);
// Create a blob client for interacting with the blob service.
blobClient = storageAccount.CreateCloudBlobClient();
blobContainer = blobClient.GetContainerReference(blobContainerName);
blobContainer.CreateIfNotExistsAsync();
blobContainer.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileName = parsedContentDisposition.FileName;
CloudBlockBlob blob = blobContainer.GetBlockBlobReference(fileName);
blob.UploadFromStreamAsync(file.OpenReadStream());
}
//HTML文件
@Html.Label(“图像”)
&时代;
$(#SaveDetailsId”)。在(“单击”,函数(){
var formdata=new formdata();
var table=$(“#ItemListTable”).DataTable();
$.each(表数据、函数(索引、项){
name='ItemList['+index+'].SkuList';//构造名称
值=项目[0];
});
formdata.append(“ImageFile”,jQuery(“文件”).get(0.files[0]);
$.ajax({
//标题:{
//“接受”:“应用程序/json”,
//“内容类型”:“应用程序/json”
//},
url:“/Test/Test”,
类型:“POST”,
数据:formdata,
contentType:false,
processData:false,
成功:功能(响应){
...
});
});
//视图模型
公开课考试
{
公共文件ImageFile{get;set;}
.
.
.
}
//MVC控制器
[HttpPost]
公共异步任务BuyerCreative([FromForm]Test\u viewModel)
{
_viewModel.Ad=\u viewModel.Ad;
使用(var client=new HttpClient())
{
//传递服务基url
client.BaseAddress=新Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
HttpResponseMessage Res=wait client.postsjsonasync(“api/Test/Test”,u viewModel);
如果(Res.IsSuccessStatusCode)
{
}
//返回要查看的员工列表
返回视图(_viewModel);
}
}
//如果有办法绑定ViewModel而不是JObject,请告诉我
//WEbApi
[路线(“api/测试/测试/”)]
[HttpPost]
公共IActionResult测试([FromBody]作业对象数据)
{
尝试
{
_存储库。添加详细信息(数据);
返回Ok();
}
捕获(异常PEException)
{
返回BadRequest(pException.Message);
}
}
//最后是我的存储库
公共void AddDetails(作业对象数据)
{
DBContext.Items _Items=new DBContext.Items();
_items.Number=Convert.ToInt32(((JValue)data.GetValue(“Number”)).Value);
//我被困在这里,如何获取文件,我尝试了各种选择
ifformfile文件=(ifformfile)((JValue)data.GetValue(“ImageFile”);
CloudStorageAccount-storageAccount=CloudStorageAccount.Parse(_connectionString);
//创建一个blob客户端,用于与blob服务交互。
blobClient=storageAccount.CreateCloudBlobClient();
blobContainer=blobClient.GetContainerReference(blobContainerName);
blobContainer.CreateIfNotExistsAsync();
SetPermissionsAsync(新的BlobContainerPermissions{PublicAccess=BlobContainerPublicAccessType.Blob});
var fileContent=reader.ReadToEnd();
var parsedContentDisposition=ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileName=parsedContentDisposition.fileName;
CloudBlockBlob blob=blobContainer.GetBlockBlobReference(文件名);
UploadFromStreamAsync(file.OpenReadStream());
}
既然您提到了属性,那么假设有一个类具有属性:
public class MyData
{
public IFormFile File { get; set; }
}
我现在可以在控制器中使用它:
public IActionResult UploadFile([FromForm]MyData data)
{
}
您的
数据.File
现在将包含该文件,只要您使用右键File
传递表单数据即可。首先,不要绑定到JObject
。创建真实视图模型并绑定到该模型
public class ItemViewModel
{
public int Number { get; set; }
public byte[] File { get; set; }
}
然后:
其次,要通过JSON发布文件,您必须将其作为base64编码的字节[]
(这将使其成为字符串)发送。modelbinder将自动将其base64解码回真实的字节[]
,如果您通过视图模型将其绑定到该文件
如果不想在客户端对其进行base64编码,则必须将其作为多部分/表单数据发布,在这种情况下,需要将发布的文件绑定到IFormFile
。这意味着您需要将上面视图模型类中的file
属性更改为:
public IFormFile File { get; get; }
这通常直接来自控制器。文件来自何处?Hi@Chris Pratt,这就是我没有被卡住的地方,真正的问题是调用web Api,它需要JObject,我已经按问题编辑了,请检查。问题首先是绑定到JObject。让modelbinder处理绑定和强制转换,因为它需要ould。您还可以获得内置验证,而JObject根本没有这种功能。一旦您有了一个绑定到的真实类,您只需要一个byte[]或ifformfile属性,这取决于您发送的内容(即JSON或表单数据)嗨,chris patt,我没听懂你的意思,我用的是Jobject,因为除了模型cla之外,thr是无法绑定的
public IFormFile File { get; get; }