我在实现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 > )
{
var file = provider.FileData[];//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("\\") + );
} 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 = ;
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客户端。

WebApi和Andriod对接上传和下载文件的更多相关文章

  1. WebApi使用二进制方式上传和下载文件

    using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; usi ...

  2. SecureCRT上传和下载文件

    SecureCRT上传和下载文件(下载默认目录) SecureCR 下的文件传输协议有ASCII .Xmodem .Ymodem .Zmodem ASCII:这是最快的传输协议,但只能传送文本文件. ...

  3. 11、只允许在主目录下上传和下载文件,不允许用putty登录

    创建用户xiao,   使其只允许在用户主目录 (/var/www/html)下上传和下载文件,不允许用putty登录 (为了安全起见,不给过多的权限) 1.创建xiao用户 [root@localh ...

  4. 每天一个linux命令(26):用SecureCRT来上传和下载文件

    用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...

  5. 利用SecureCRT上传、下载文件(使用sz与rz命令),超实用!

    利用SecureCRT上传.下载文件(使用sz与rz命令),超实用! 文章来源:http://blog.csdn.net/dongqinliuzi/article/details/39623169 借 ...

  6. Linux--用SecureCRT来上传和下载文件

    SecureCRT下的文件传输协议有以下几种:ASCII.Xmodem.Ymodem.Zmodem ASCII:这是最快的传输协议,但只能传送文本文件. Xmodem:这种古老的传输协议速度较慢,但由 ...

  7. secureCRT简单上传、下载文件记录

    secureCRT简单上传.下载文件记录: 1)sz下载 -y 覆盖 2)rz上传 -y 覆盖 3)以上两个命令属于安装时包含在“Dial-up Networking Support"组中 ...

  8. 每天一个linux命令(26)--用SecureCRT来上传和下载文件

    用SSH管理Linux 服务器时经常需要远程与本地之间交互文件,而直接使用 SecureCRT 自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmod ...

  9. 每天一个linux命令(26):用SecureCRT来上传和下载文件(转载自竹子)

    用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...

随机推荐

  1. 让你的ansible飞起来

    一.SSH Multiplexing 1 配置 vim /etc/ssh/ssh_config Host * GSSAPIAuthentication yes # If this option is ...

  2. poj 3348 Cows 凸包 求多边形面积 计算几何 难度:0 Source:CCC207

    Cows Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 7038   Accepted: 3242 Description ...

  3. json 解析double类型多出几位小数,利用NSDecimalNumber修复 , 服务器返回的数据,用数据类型接收(int,NSNumber)?

     后台返回float类型数据8.2,实际用AFN的json解析后得到8.1999999999,该怎么处理呢? 开发中处理处理价格金额问题, 后台经常返回float.double类型, 打印或转成NSS ...

  4. New Concept English three(18)

    speed:31w/m 56 words Modern sculpture rarely surprises us any more. The idea that modern art can onl ...

  5. Windows 2003/XP 连接vmware 5.5错误

    参考文章:http://www.mamicode.com/info-detail-7253.html 补丁下载地址参考: http://support.microsoft.com/hotfix/KBH ...

  6. 一个好工具-everything-可以找到浏览器的所有缓存

    下载路径http://www.voidtools.com/downloads/ 我用它来寻找浏览器缓存的google瓦片.

  7. .net MVC3 架构搭建描述

    用visual studio创建.net MVC3 web项目时,默认情况下是将Views,Controllers,Models创建在一个项目中. 需要把Controllers和Models做为两个独 ...

  8. ss-libev 源码解析local篇(5):ss-local之remote_send_cb

    remote_send_cb这个回调函数的工作是将从客户端收取来的数据转发给ss-server.在之前阅读server_recv_cb代码时可以看到,在STAGE_STREAM阶段有几种可能都会开启r ...

  9. 移动端 css 禁止长按屏幕选中

    *{ -webkit-touch-callout:none; -webkit-user-select:none; -khtml-user-select:none; -moz-user-select:n ...

  10. Google内部培训过1.8万人的机器学习速成课

    什么是(监督)机器学习?简而言之,它是以下几点: ML系统学习如何组合输入以产生对从未见过的数据的有用预测. 我们来探讨基本的机器学习术语. 标签 一个标签是我们预测物品的属性,比如变量y在简单线性回 ...