Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This isn't how I had to implement file upload at all. I had an action method with no parameters that used the current Request object to dive into the collection of posted files.</p> <p>Some sample code from my implementation:</p> <pre><code>[AcceptVerbs(HttpVerbs.Post)] public ContentResult Upload() { if (Request.Files.Count &gt; 0 &amp;&amp; Request.Files[0].ContentLength &gt; 0) { HttpPostedFileBase postedFile = Request.Files[0]; // Do something with it } } </code></pre> <p>Of course, writing tests for this becomes a PITA. You have to mock several objects in order to get it to work, for example:</p> <pre><code>var mockHttpContext = mocks.StrictMock&lt;HttpContextBase&gt;(); var mockRequest = mocks.StrictMock&lt;HttpRequestBase&gt;(); var postedFile = mocks.StrictMock&lt;HttpPostedFileBase&gt;(); var postedFileKeyCollection = mocks.StrictMock&lt;HttpFileCollectionBase&gt;(); mockHttpContext.Expect(x =&gt; x.Request).Return(mockRequest).Repeat.Any(); mockRequest.Expect(x =&gt; x.Files).Return(postedFileKeyCollection).Repeat.Any(); postedFileKeyCollection.Expect(x =&gt; x[0]).Return(postedFile).Repeat.Any(); postedFileKeyCollection.Expect(x =&gt; x.Count).Return(1); postedFile.Expect(f =&gt; f.ContentLength).Return(1024); postedFile.Expect(f =&gt; f.InputStream).Return(null); </code></pre> <p>It would be easier to create an interface into the posted files and only mock that, with a concrete implementation injected into your controller using IoC.</p> <p>I think this was largely based off of this post: <a href="http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx" rel="nofollow noreferrer">Implementing HTTP File Upload with ASP.NET MVC including Tests and Mocks</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload