jjzjj

c# - 如何将文件上传到 Web API 服务器并将参数发送到操作?

coder 2024-06-03 原文

美好的一天!

我正在从事 ASP.NET Web API 2 项目。在某个时候需要上传一些文件。这些文件需要链接到某个 FileModel(我们自己的类)。因此,客户端需要将 IEnumerable 作为参数发送,将文件作为内容发送。因为它是一个 RESTful API,所以两者都必须在同一个请求中发送。

我们能想到的最好的是跟随 Controller Action :

public async Task<HttpResponseMessage> Add([FromUri] IEnumerable<FileModel> fileModels)
{
   // REQUEST INTEGRITY TESTING

   var streamProvider = new CustomMultipartFormDataStreamProvider(fileSavePath, fileModels);
   // Read the MIME multipart content using the stream provider we just created.
   var work = await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(async t =>
        {
            // SOME WORK DONE AFTER SAVING THE FILES TO THE HARD DRIVE
        }

}

问题如下:上传的文件带有“multipart/form-data”Content-Type header 。 在服务器端操作文件之前,我们需要知道 FileModels 的内容。如果我们使用MultipartFormDataStreamProvider,我们只能在文件已经保存到硬盘后才能访问非文件参数。

我们能找到的唯一解决方法是在 URL 中发送 IEnumerable 参数。但鉴于 URL 的最大长度有限,这不是一个可靠的方法。

问题是:有没有办法同时提交 IEnumerable< filemodel=""> fileModels 参数和 请求正文 中的文件并获得对 fileModels 的访问权访问文件之前的参数?我们还希望能够使用 HttpContext.Current.Request.Files.Count;

我们当前用于文件上传的 jQuery 如下所示(出于早期测试目的,它仅支持一个文件上传):

$('#Upload').click(function(e) {
            e.preventDefault();

            var headers = new Array();
            headers["SessionId"] = sessionId;

            var files = $('#fileInput').get(0).files;
            var formData = new FormData();
            formData.append("files", files[0]);

            var fileModel = $('#fileSubmission').serialize();

            $.ajax({
                url: "api/Submissions/Add/?" + fileModel,
                headers: headers,
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                dataType: 'json'
            });
        });

非常感谢!

最佳答案

很抱歉回答晚了,但我们解决了问题(我忘了我没有在这里上传答案)。基本上我们所做的是在临时位置调用 ReadAsMultiPartAsync 方法,然后从请求中提取其他参数。之后,我们验证了输入并将文件从临时位置移动到永久位置。

如果您想查看代码,这就是我们特定示例的工作方式,我相信它可以非常简单地适应任何工作案例场景:

在客户端,我们有以下表单(是的,这个实现是为了演示目的,只支持发送一个文件......而且,输入类型="file"字段确实在表单之外; fileId在我们的案例中,文本输入是手动完成的,仅用于测试目的)

<input type="file" name="data" id="fileInput" multiple="multiple" />

<form id="fileSubmission">            
    <input type="text" width="10" onchange="getFileDetails()" autocomplete="off" placeholder="FileId" name="files[0].Id" id="fileId" /> 
    <input type="hidden" name="files[0].FileName" id="FileName"/>
    <input type="hidden" name="files[0].Extension" id="Extension"/>
    <input type="hidden" name="files[0].EntityId" id="EntityId"/>
    <br /><br />
    <input type="submit" id="Upload" value="Upload" />
</form>

其中 getFileDetails() 填充其他输入字段。此外,使用以下 jQuery/Javascript 将表单发送到服务器:

$('#Upload').click(function(e) {
            e.preventDefault();

            var courseId = $('#courseId').val();
            var fileId = $('#fileId').val();
            if (!courseId || !fileId) {
                return;
            }

            var headers = new Array();
            headers["SessionId"] = sessionId;
            headers["contentType"] = "application/json; charset=UTF-8";

            var formData = new FormData();
            var opmlFile = $('#fileInput').get(0).files;

            // this is like the model we're expecting on the server
            var files = [];
            files.push({ 'Id': $('#fileId').val(), 'OriginalFileName': opmlFile[0].name, 'FileName': $('#FileName').val(), 'Extension': $('#Extension').val(), 'EntityId': $('#EntityId').val() });

            formData.append("fileModels", JSON.stringify(files));
            formData.append("File_0", opmlFile[0]);


            $.ajax({
                url: "api/Courses/" + courseId + "/Submissions/Add/",
                headers: headers,
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                dataType: 'json'
            });
        });

在服务器端,我们有以下内容:

// POST: api/Courses/{courseId}/Submissions/Add
[HttpPost]
[ValidateModelState]
[ValidateMimeMultipartContent]
[PermissionsAuthorize(CoursePermissions.CanCreateSubmissions)]
public async Task<HttpResponseMessage> Add(int courseId)
    {
        // the same as in the jQuery part
        const string paramName = "fileModels";

        // Put the files in a temporary location
        // this way we call ReadAsMultiPartAsync and we get access to the other data submitted
        var tempPath = HttpContext.Current.Server.MapPath("~/App_Data/Temp/" + Guid.NewGuid());
        Directory.CreateDirectory(tempPath);

        var streamProvider = new MultipartFormDataStreamProvider(tempPath);
        var readResult = await Request.Content.ReadAsMultipartAsync(streamProvider);

        if (readResult.FormData[paramName] == null)
        {
            // We don't have the FileModels ... delete the TempFiles and return BadRequest
            Directory.Delete(tempPath, true);
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

        // The files have been successfully saved in a TempLocation and the FileModels are not null
        // Validate that everything else is fine with this command
        var fileModels = JsonConvert.DeserializeObject<IEnumerable<FileModelExtension>>(readResult.FormData[paramName]).ToList();

        // AT THIS POINT, ON THE SERVER, WE HAVE ALL THE FILE MODELS 
        // AND ALL THE FILES ARE SAVED IN A TEMPORARY LOCATION

        // NEXT STEPS ARE VALIDATION OF THE INPUT AND THEN 
        // MOVING THE FILE FROM THE TEMP TO THE PERMANENT LOCATION

        // YOU CAN ACCESS THE INFO ABOUT THE FILES LIKE THIS:
        foreach (var tempFile in readResult.FileData)
            {
                var originalFileName = tempFile.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);

                var localTempPath = tempFile.LocalFileName;
            }

    }

我希望这对尝试使用 Post 请求一次向服务器提交文件和其他参数的任何人有所帮助! :)

注意:服务器上使用的一些属性是自定义的。 PermissionAuthorize、ValidateModelState 和 ValidateMimeMultiPartContent 是我们使用的自定义过滤器。后两者的实现受到 http://benfoster.io/blog/automatic-modelstate-validation-in-aspnet-mvc 的启发。

multipartcontent 属性只是检查 actionContext.Request.Content.IsMimeMultipartContent(),如下所示:

public class ValidateMimeMultipartContent : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.Request.Content.IsMimeMultipartContent())
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, Messages.UnsupportedMediaType);
        }
    }
}

关于c# - 如何将文件上传到 Web API 服务器并将参数发送到操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27885052/

有关c# - 如何将文件上传到 Web API 服务器并将参数发送到操作?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  4. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  5. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  6. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  7. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  8. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  9. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  10. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

随机推荐