我正试图通过IIS7将文件带到往返。
我的动作方法如下:
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");
}
我用fiddler调用它,文件在服务器上上传并创建,但是fiddler显示“response has no body”消息而不是图像(文件是indead a tif)。原始回应是
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
正如您所看到的,内容长度为零。为什么图像不会回来?
答案 0 :(得分:0)
您应该将fileStream
实例的位置重置为0,然后再将其返回到结果中。
说明
复制从当前流中的当前位置开始,并且在复制操作完成后不会重置目标流的位置。
如果存在异常,则添加try/catch
以处置FileStream
,然后重新抛出。
包含更改的代码
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;
}
}