![](/img/trans.png)
[英]Xamarin form - how to upload and retrieve image using sql server web api
[英]How to download image file stored in the form of bytes in SQL server using Web API
嘗試下載以字節形式存儲在sql server中的圖像,並能夠下載該圖像,但是我收到了損壞的圖像,無法打開下載的圖像
這是我的代碼
data.imageData是從SQl服務器檢索的圖像的Byte []數據
data.imageName是文件名
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中變成的字節數組)執行以下操作:
如果您有這樣的Document類:
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");
}
將文件流返回到瀏覽器的位置,瀏覽器會將其呈現為圖像
會建議參考ASP.NET MVC控制器可以返回圖像嗎? 您可以根據需要嘗試多種選擇
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.