使用ASP.NET Web API在服务器Webfolder上上传文件并同时发布JSON数据 [英] upload file on server webfolder and post json data at the same using asp.net web api

查看:85
本文介绍了使用ASP.NET Web API在服务器Webfolder上上传文件并同时发布JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用asp.net Web API同时上传文件和发布json数据,但我无法弄清楚如何为控制器编码以接收json数据和文件请求,也无法弄清楚该怎么做设置邮递员进行测试.

 公共异步任务< JObject>保存(验证值){} 

解决方案

从Web表单上载文件到服务器需要一种不同的方法,特别是当您要上载具有其他模型数据的文件时.

在客户端上选择的文件不能作为JSON提交到服务器.因此,我们需要将表单作为集合提交给服务器.我们也不能使用 application \ json 作为内容类型.

请考虑以下示例.ASP.NET MVC应用程序示例演示了该示例.

您需要做的第一件事是将File对象添加为模型类的一部分.

 公共类ClientDocument{public int ID {get; set;}public int ClientId {get; set;}公共字符串Title {get; set;}//下面的属性用于将文件从客户端获取到服务器.公共IFormFile文件{get; set;}} 

然后,您需要在视图中创建一个表单.假定视图的Model类型设置为上述类.

 < form id ="someForm"method ="post">@ Html.HiddenFor(m => m.ClientId)< table>< tr>< td>@ Html.LabelFor(m => m.Title)</td>< td>@ Html.TextFor(m => m.Title)</td></tr>< tr>< td>@ Html.LabelFor(m => m.File)</td>< td>//下面的代码行将呈现文件控制,用户可以在其中从本地计算机选择文件.@ Html.TextBoxFor(m => m.File,新的{Type ="file"})</td></tr>< tr>< td colspan ="2">< button type =按钮"onclick ="SubmitForm();"> Submit</button></td></tr></table></form> 

以下是用于提交表单的JavaScript代码.JavaScript中的SubmitForm函数会将表单转换为FormData对象.

FormData是一个JavaScript对象,它以键/值对的形式表示数据.创建FormData对象后,我们会将其发布到服务器.如上所述,我们不能使用 application \ json 内容类型,我们需要使用 multipart/form-data 作为有效负载的编码类型.

 < script>函数SubmitForm(){如果($(#someForm").valid()){var form = $(#someForm")[0];var data = new FormData(form);$ .ajax({类型:"POST",编码类型:"multipart/form-data",网址:"http://www.somedomain.com/api/ClientDocument/Save",数据:数据,processData:否,contentType:false,快取:false,beforeSend:function(){//显示等待图标.},成功:功能(数据){//隐藏等待图标;//在用户界面中显示响应.},错误:函数(xhr,状态,errorThrown){console.log('ERROR:'+ xhr.responseText);}});}}</script> 

现在在服务器端,控制器操作如下所示.

 公共IActionResult保存(ClientDocument模型){尝试{//访问文件属性以将其保存在服务器上或上传到某些存储var fileObject = model.File;var tartgetLocation ="D:\\ ClientDocuments \\"+ fileObject.FileName;使用(var stream = new FileStream(tartgetLocation,FileMode.Create)){fileObject.CopyTo(stream);}//编写代码以将信息保存到数据库.}抓住(前例外){//处理异常返回Json(new {Status ="Failed"}));}返回Json(new {Status ="Success"}));} 

我知道这不是您要找的确切答案.但这应该为您提供一个有关如何解决问题并在使用案例中应用相同技术(如果适用的话)的想法.

I want to upload files and post json data at the same using asp.net web api, i am not able to figure out how to code for controller to receive json data and file request also not able to figure out how to do setting in postman for testing the same.

public async Task<JObject> Save(Validate val)
{
}

解决方案

Uploading a file from web form to server requires a different approach specially when you want to upload file with other model data.

Files selected on the client can not be submitted as JSON to the server. So we need to submit the form as a Collection to the server. We also can not use application\json as content-type.

Consider following example. The example is demonstrated with ASP.NET MVC application example.

First thing you need to do is add the File object as part of the model class.

public class ClientDocument
{
    public int Id {get;set;}
    public int ClientId {get;set;}
    public string Title {get;set;}
    // Below property is used for getting file from client to the server.
    public IFormFile File {get;set;}
}

Then you need to create a form in the View. Assume that the view has Model type set to the above class.

<form id="someForm" method="post">
    @Html.HiddenFor(m => m.ClientId)
    <table>
        <tr>
            <td>
                @Html.LabelFor(m => m.Title)
            </td>
            <td>
                @Html.TextFor(m => m.Title)
            </td>
       </tr>
       <tr>
           <td>
               @Html.LabelFor(m => m.File)
           </td>
           <td>
               //Following line of code will render file control, where user can select file from the local machine.
               @Html.TextBoxFor(m => m.File, new { Type = "file" })
           </td>
       </tr>
       <tr>
          <td colspan="2">
              <button type="button" onclick="SubmitForm();">Submit</button>
          </td>
       </tr>
    </table>
</form>

Following is the JavaScript code for submitting the form. SubmitForm function in the JavaScript will convert the form to a FormData object.

FormData is a JavaScript object which represents data as a colleciton of Key/value pairs. Once the FormData object is created, we will post it to the server. As I mentioned above we can not use application\json content-type, we need to use multipart/form-data as encodingtype of the payload.

<script>
    function SubmitForm() {
        if ($("#someForm").valid()) {
             var form = $("#someForm")[0];
             var data = new FormData(form);
             
             $.ajax({
                type: "POST",
                enctype: 'multipart/form-data',
                url: "http://www.somedomain.com/api/ClientDocument/Save",
                data: data,
                processData: false,
                contentType: false,
                cache: false,
                beforeSend: function () {
                    // show waiting icon.
                },
                success: function (data) {
                    //Hiding waiting icon;
                    //Display the response in the UI.
                },
                error: function (xhr, status, errorThrown) {
                    console.log('ERROR : ' + xhr.responseText);
                }
            });
        }
    }
</script>

Now at the server end the controller action would look like following.

public IActionResult Save(ClientDocument model)
{
        try
        {
            //Access File Property to save it on server or upload to some storage
            var fileObject = model.File;
            var tartgetLocation = "D:\\ClientDocuments\\" + fileObject.FileName;
            
             using (var stream = new FileStream(tartgetLocation , FileMode.Create))
            {
                fileObject.CopyTo(stream);
            }
            
            // Write code to save information to database.
        }
        catch (Exception ex)
        {
            //Handle Exception
            return Json(new {Status= "Failed"});
        }

        return Json( new {Status= "Success"});
    }

I know that this is not the exact answer you might be looking for. But this should give you an idea about how to approach the problem and apply the same technique if applicable in your use case.

这篇关于使用ASP.NET Web API在服务器Webfolder上上传文件并同时发布JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆