WebApi和Andriod对接上传和下载文件

我在实现webapi和Andriod客户端上传下载文件的时候默认的是以流的形式返回的,下面我就贴出最近在研究的对接文件的上传和下载代码以供各位大侠们参考:

上传文件接口:

 [HttpPost]
        public async Task<HttpResponseMessage> PostReplayInfo()
        {

            //HttpPostedFile file = HttpContext.Current.Request.Files[0];
            if (!Request.Content.IsMimeMultipartContent("form-data"))
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            HttpResponseMessage response = null;

            //string strPath = "F:\项目\\" + file.FileName;
            try
            {
                // 设置上传目录
                var provider = new MultipartFormDataStreamProvider(@"F:\项目");
                // 接收数据,并保存文件
                var bodyparts = await Request.Content.ReadAsMultipartAsync(provider);
                response = Request.CreateResponse(HttpStatusCode.Accepted);

                string str = "";
                msgCont msgcont=new msgCont();
                if (provider.FileData.Count > 0)
                {
                    var file = provider.FileData[0];//provider.FormData 
                    FileInfo fileinfo = new FileInfo(file.LocalFileName);

                    string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
                    msgcont.Accessory = orfilename;
                    msgcont.AccessoryID = file.LocalFileName.Substring(file.LocalFileName.LastIndexOf("\") + 1);
                }
              
                foreach (var key in provider.FormData.AllKeys)
                {//接收FormData  
                    
                    str =provider.FormData["requestData"].ToString();
                }
                StringBuilder strSql = new StringBuilder();
                JSONObject json = JSONConvert.DeserializeObject(str);
                msgcont.MsgPersonID = int.Parse(json["MsgPersonID"].ToString());
                msgcont.Title = json["Title"].ToString();
                msgcont.SendDate = DateTime.Now;
                msgcont.Status = 0;
                msgcont.Content = json["Content"].ToString();
                msgcont.SendTo = json["SendTo"].ToString();
                msgcont.SendToID = json["SendToID"].ToString();
                msgcont.ReplayId = int.Parse(json["MessageID"].ToString());
                msgcont.ProjectID = int.Parse(json["ProjectID"].ToString());
               // msgcont.Accessory = orfilename;
               db.msgCont.Add(msgcont);
               db.SaveChanges();
              

               string s = "{"code":"1","messge":"成功"}";
               HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(s, Encoding.GetEncoding("UTF-8"), "application/json") };
               return result;
            }
            catch (Exception ex)
            {
                string s = "{"code":"0","messge":"失败," + ex.Message + ""}";
                HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(s, Encoding.GetEncoding("UTF-8"), "application/json") };
                return result;
            }
           

        }

这是一个上传文件并将记录插入到对应的数据库的列子,Andriod客户端传过来的时一个MultiplePart的形式,所以在webapi服务器端获取数据的时候需要将参数进行分解,获取到对应的文件流形式之后。

文件下载接口:

 /// <summary>  
        /// 文件下载  
        /// </summary>  
        /// <param name="filePath "></param>  
        /// <returns></returns>  
        [HttpGet]
        public HttpResponseMessage GetDownLoad(string requestData)
        {

            StringBuilder strSql = new StringBuilder();
            JSONObject json = JSONConvert.DeserializeObject(requestData);
            string LastName = System.IO.Path.GetExtension(json["fileName"].ToString());
            string customFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + LastName;
           
            string filePath = "F:\项目\"+json["fileName"].ToString();
            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;
        }

在获取到从客户端传过来的文件名之后,访问服务器端文件,并以流的形式返回给Andriod客户端。

原文地址:https://www.cnblogs.com/syfblog/p/4773450.html