我从API网络服务下载文件时遇到问题。当我在高级休息客户端测试它时。我没有收到我的档案但是我得到了字符。我的http://41.128.183.109:1212/api/Data/get filename = claims.jpg
这是我的代码:
public HttpResponseMessage get ([FromUri]string filename)
{
string path = HttpContext.Current.Server.MapPath("~/TransientStorage/" + filename);
if (!File.Exists(path))
{
throw new HttpResponseException( HttpStatusCode.NotFound);
}
try
{
MemoryStream responseStream = new MemoryStream();
Stream fileStream = File.Open(path, FileMode.Open);
bool fullContent = true;
if (this.Request.Headers.Range != null)
{
fullContent = false;
// Currently we only support a single range.
RangeItemHeaderValue range = this.Request.Headers.Range.Ranges.First();
// From specified, so seek to the requested position.
if (range.From != null)
{
fileStream.Seek(range.From.Value, SeekOrigin.Begin);
// In this case, actually the complete file will be returned.
if (range.From == 0 && (range.To == null || range.To >= fileStream.Length))
{
fileStream.CopyTo(responseStream);
fullContent = true;
}
}
if (range.To != null)
{
// 10-20, return the range.
if (range.From != null)
{
long? rangeLength = range.To - range.From;
int length = (int)Math.Min(rangeLength.Value, fileStream.Length - range.From.Value);
byte[] buffer = new byte[length];
fileStream.Read(buffer, 0, length);
responseStream.Write(buffer, 0, length);
}
// -20, return the bytes from beginning to the specified value.
else
{
int length = (int)Math.Min(range.To.Value, fileStream.Length);
byte[] buffer = new byte[length];
fileStream.Read(buffer, 0, length);
responseStream.Write(buffer, 0, length);
}
}
// No Range.To
else
{
// 10-, return from the specified value to the end of file.
if (range.From != null)
{
if (range.From < fileStream.Length)
{
int length = (int)(fileStream.Length - range.From.Value);
byte[] buffer = new byte[length];
fileStream.Read(buffer, 0, length);
responseStream.Write(buffer, 0, length);
}
}
}
}
// No Range header. Return the complete file.
else
{
fileStream.CopyTo(responseStream);
}
fileStream.Close();
responseStream.Position = 0;
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = fullContent ? HttpStatusCode.OK : HttpStatusCode.PartialContent;
response.Content = new StreamContent(responseStream);
return response;
}
catch (IOException)
{
throw new HttpResponseException( HttpStatusCode.InternalServerError);
}
}
答案 0 :(得分:0)
我认为你收到了你的档案。这就是jpg文件的样子(至少标题看起来不错)。但它是字节格式,不会渲染为图像。尝试将其作为* .jpg文件存储在硬盘驱动器上或使用img标签显示。
答案 1 :(得分:0)
在响应对象中添加内容类型。
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = fullContent ? HttpStatusCode.OK : HttpStatusCode.PartialContent;
response.Content = new ByteArrayContent(responseStream.ToArray());
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return response;