WepAPI下載與上傳文件

1、上傳文件,代碼是沒問題的,但是我在調用的時候出現了iframe跨域問題,(沒有解決),在不牽扯主頁面套用子頁面的情況下使用是可以的。

代碼:

 #region 上傳文件
        [HttpPost]       
        public HttpResponseMessage UpLoadFile()
        {
            // 檢查是否是 multipart/form-data
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

string json;
            string productName = HttpContext.Current.Request.Form["TempProductName"];
            HttpPostedFile file = HttpContext.Current.Request.Files["TempLicense"];
            if (file != null)
            {

if (file.ContentLength / 1024 > 100)//不能超過100KB
                {
                    json = "{\"success\":0,\"msg\":\"The file is too large\"}";
                }
                else
                {

var fileSavePath = HttpContext.Current.Server.MapPath("/") + "TempLicenseFile/" + productName + "/";
                    if (Directory.Exists(fileSavePath))
                    {
                        Directory.Delete(fileSavePath, true);
                    }

 Directory.CreateDirectory(fileSavePath);
                    String filePath = fileSavePath + file.FileName;
                    file.SaveAs(filePath);
                    json = "{\"success\":1,\"msg\":\"success\"}";
                }
            }

 else
            {
                json = "{\"success\":0,\"msg\":\"no file\"}";
            }
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(json, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }     
        #endregion

2、下載文件。當時是給安卓那邊調用。

代碼:

         /// <summary>
        /// 下載文件
        /// </summary>
        /// <param name="filePath">文件路徑</param>
        /// <param name="name">客戶端保存的文件名</param>
        /// <returns></returns>

public HttpResponseMessage DownLoad(string filePath, string name)
        {
            string customFileName = name;
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            HttpResponseMessage response = new HttpResponseMessage();
            response.Content = new StreamContent(fileStream);

 response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = customFileName;
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            response.Content.Headers.ContentLength = new FileInfo(filePath).Length;
            return response;
      }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章