C# 如何使用Web API下载SQL server中以字节形式存储的图像文件
正在尝试下载存储在sql server中以字节形式存储的映像,并且能够下载映像,但是我得到的映像已损坏,无法打开下载的映像 这是我的密码 data.imageData是从SQl server检索的映像的字节[]数据 data.imageName是文件名C# 如何使用Web API下载SQL server中以字节形式存储的图像文件,c#,asp.net-web-api,asp.net-web-api2,C#,Asp.net Web Api,Asp.net Web Api2,正在尝试下载存储在sql server中以字节形式存储的映像,并且能够下载映像,但是我得到的映像已损坏,无法打开下载的映像 这是我的密码 data.imageData是从SQl server检索的映像的字节[]数据 data.imageName是文件名 public class Attachmets { public byte[] Imagedata {get;set;} public string ImageName {get;set;} } public static
public class Attachmets
{
public byte[] Imagedata {get;set;}
public string ImageName {get;set;}
}
public static HttpResponseMessage DownloadImage(Attachments data, bool isInline)
{
isInline = false;
var response = new HttpResponseMessage();
var memoryStream = new MemoryStream(data.ImageData);
response.Content = new StreamContent(memoryStream);
var headers = response.Content.Headers;
headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
headers.ContentDisposition =
new ContentDispositionHeaderValue(isInline ? DispositionTypeNames.Inline : DispositionTypeNames.Attachment)
{
FileName = Path.GetFileName(data.ImageName)
};
return response;
}
如果您正在使用Web API 2(如标记的那样)并从SQL Server检索数据(尽管令人困惑的是,问题代码中没有显示这一点,您似乎只是返回从客户端提交的数据,但我们将把它放在一边),您可以使用FileResult和字节数组执行类似的操作(这是SQL Server中的映像或二进制字段在.NET中的格式):
如果您有这样的文档类:
public class Document
{
public byte[] Data { get; set; }
public string FileName { get; set; }
public string MimeType { get; set; }
}
public IHttpActionResult Download(int id) { //id will be the documentID to retrieve from the database
//Then, here you place your database code to retrieve the correct data from the database including the binary file data, a file name and a suitable Mime Type.
//Then populate that into an instance of the Document class (calling the variable "doc" and then simply return it to the client like this:
return new FileResult(doc.Data, doc.FileName, doc.MimeType);
}
您可以有如下控制器操作方法:
public class Document
{
public byte[] Data { get; set; }
public string FileName { get; set; }
public string MimeType { get; set; }
}
public IHttpActionResult Download(int id) { //id will be the documentID to retrieve from the database
//Then, here you place your database code to retrieve the correct data from the database including the binary file data, a file name and a suitable Mime Type.
//Then populate that into an instance of the Document class (calling the variable "doc" and then simply return it to the client like this:
return new FileResult(doc.Data, doc.FileName, doc.MimeType);
}
我不确定您在客户端是如何处理的。但是您直接绑定了响应。这应该可以工作
public FileResult DownloadImage(Attachments data, bool isInline)
{
...
...
return new FileStreamResult(new FileStream(path, FileMode.Open), "image/jpeg");
}
将文件流返回到浏览器,浏览器将其渲染为图像
建议您根据需要在有很多选项可供尝试的地方进行引用。数据参数的类型是附件…这是什么?您确定数据成员是编码的八位字节流,因为这是您告诉浏览器的。如果不是,则垃圾输入,垃圾输出。@GaRymgill update my question DownloadImage是我传递数据的函数名。Attachments是包含imagedata和imageName的类文件