/// <summary>
/// 項目文件夾下路徑 返回流類型數據,如:圖片類型 /// </summary>
/// <returns></returns>
public HttpResponseMessage GetImg() { // ~/ ImageFile / 001.png //項目文件夾下路徑
var imgPath = System.Web.Hosting.HostingEnvironment.MapPath("~/ImageFile/2.jpg"); // 從圖片中讀取byte
var imgByte = File.ReadAllBytes(imgPath); // 從圖片中讀取流
var imgStream = new MemoryStream(File.ReadAllBytes(imgPath)); var resp = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(imgStream) //或者 // Content = new ByteArrayContent(imgByte)
}; resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg"); return resp; }
[HttpGet] public HttpResponseMessage SelectUploadFile() { Image img = Image.FromFile(@"C:\ImageFile\2.jpg"); MemoryStream ms = new MemoryStream(); img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new ByteArrayContent(ms.ToArray()); result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); //設置http響應上的Content-Type 爲image/Png媒體類型
return result; }
異步操做獲取文件圖片異步
[Route("Main")] [HttpGet] public async Task<HttpResponseMessage> GetMain(string Ordernumber, int seq = 1) { return await Task.FromResult<HttpResponseMessage>(GetFileImage("main", Ordertnumber, seq)); } private HttpResponseMessage GetFileImage(string type, string Ordernumber, int seq) { string basePath = @"C:\ImageFile\"; string filePath = basePath + type + "\\_" + type + "_" + seq.ToString() + ".png"; Image img = Image.FromFile(filePath); MemoryStream ms = new MemoryStream(); img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new ByteArrayContent(ms.ToArray()); result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/Png"); return result; }