WepAPI下载与上传文件

来源:互联网 发布:网络有什么坏处 编辑:程序博客网 时间:2024/06/05 06:13

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;
      }
0 0
原创粉丝点击