C# webapi 上傳下載圖片

客戶端上傳文件web

string url = url + "webUploadFile";
            Uri server = new Uri(url);
            HttpClient httpClient = new HttpClient();

            MultipartFormDataContent multipartFormDataContent = new MultipartFormDataContent();

            StreamContent streamConent = new StreamContent(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read));

            multipartFormDataContent.Add(streamConent, "jpg", fileName);

            HttpResponseMessage responseMessage = httpClient.PostAsync(server, multipartFormDataContent).Result;
            return responseMessage;

 

服務端接收文件json

 
 

[Route("webUploadFile"), System.Web.Http.HttpPost]
public HttpResponseMessage webUploadFile()app

{url

  if (HttpContext.Current.Request.Files.AllKeys.Any()) {var httpPostedFiles = HttpContext.Current.Request.Files; if (httpPostedFiles != null && httpPostedFiles.Count > 0) { // 獲取文件
                        HttpPostedFile httpPostedFile = httpPostedFiles[0]; string fileExtension = ".jpg";// Path.GetExtension(httpPostedFile.FileName);// 文件擴展名
                        string fileId = "11"; string filePath = uploadPath + fileId + fileExtension;// 上傳路徑
 httpPostedFile.SaveAs(filePath); string jsonres = "{\"code\":\"200\",\"message\":\"文件上傳成功\", \"data\":{ \"fileUrl\":\"" + downloadurl+ "webDownloadFile?fileId=" + fileId + "\"}}"; return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(jsonres, System.Text.Encoding.UTF8, "application/json")}; } }
}

 

服務端下載文件spa

[Route("webDownloadFile"), System.Web.Http.HttpGet]   
        public HttpResponseMessage webDownloadFile()
        {
            if (HttpContext.Current.Request.Params.Count > 0 && HttpContext.Current.Request["fileId"] != null)
            {
                string fileId = HttpContext.Current.Request["fileId"];
                string fileName = fileId + ".jpg";

                string path = uploadPath + fileName;
                if (!File.Exists(path))
                {
                    return new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(Common.ReturnMessage("404", "文件不存在"), System.Text.Encoding.UTF8, "application/json") };
                }

                HttpResponseMessage result = null;

                FileStream fs = new FileStream(path, FileMode.Open);

                result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new StreamContent(fs);
                result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");

                return result;
            }

            return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(Common.ReturnMessage("400", "文件下載失敗"), System.Text.Encoding.UTF8, "application/json") };
        }
相關文章
相關標籤/搜索