Reputation: 754
I am trying to bring a file on a roundtrip through an IIS7.
I got my action method as follows:
public ActionResult GiveItBack()
{
var inFile = Request.Files[0];
var fileStream = new FileStream(Path.GetTempPath() + "uploadedFile.tif", FileMode.OpenOrCreate);
inFile.InputStream.Position = 0;
inFile.InputStream.CopyTo(fileStream);
return new FileStreamResult(fileStream, "image/tiff");
}
I call it with fiddler, file is uploaded and created on the server, but fiddler shows a "response has no body" message instead of the image (file is indead a tif). Raw response is
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: image/tiff
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcQXJiZWl0c2JlcmVpY2hcUHJvamVrdGUgLSBmcmVtZFxBbXBzMyBQaXBlc1xLaXR0ZWxiZXJnZXIuQU1QUzMuV2ViU2VydmljZVxDb21tYW5kQ2hhaW5cRG9pbmc=?=
X-Powered-By: ASP.NET
Date: Wed, 14 Jun 2017 12:48:22 GMT
Content-Length: 0
As you can see the content length is zero. Why is the image not coming back?
Upvotes: 3
Views: 1743
Reputation: 62213
You should reset the Position of the fileStream
instance back to 0 before returning it in the result.
From CopyTo documentation
Remarks
Copying begins at the current position in the current stream, and does not reset the position of the destination stream after the copy operation is complete.
Also add a try/catch
to dispose of the FileStream
if there is an exception and then rethrow.
Code with changes
public ActionResult GiveItBack()
{
var inFile = Request.Files[0];
var fileStream = new FileStream(Path.GetTempPath() + "uploadedFile.tif", FileMode.OpenOrCreate);
try {
inFile.InputStream.Position = 0;
inFile.InputStream.CopyTo(fileStream);
fileStream.Position = 0;
return new FileStreamResult(fileStream, "image/tiff");
} catch {
fileStream.Dispose();
throw;
}
}
Upvotes: 1