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 > )
{
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对接上传和下载文件的更多相关文章
- WebApi使用二进制方式上传和下载文件
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; usi ...
- SecureCRT上传和下载文件
SecureCRT上传和下载文件(下载默认目录) SecureCR 下的文件传输协议有ASCII .Xmodem .Ymodem .Zmodem ASCII:这是最快的传输协议,但只能传送文本文件. ...
- 11、只允许在主目录下上传和下载文件,不允许用putty登录
创建用户xiao, 使其只允许在用户主目录 (/var/www/html)下上传和下载文件,不允许用putty登录 (为了安全起见,不给过多的权限) 1.创建xiao用户 [root@localh ...
- 每天一个linux命令(26):用SecureCRT来上传和下载文件
用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...
- 利用SecureCRT上传、下载文件(使用sz与rz命令),超实用!
利用SecureCRT上传.下载文件(使用sz与rz命令),超实用! 文章来源:http://blog.csdn.net/dongqinliuzi/article/details/39623169 借 ...
- Linux--用SecureCRT来上传和下载文件
SecureCRT下的文件传输协议有以下几种:ASCII.Xmodem.Ymodem.Zmodem ASCII:这是最快的传输协议,但只能传送文本文件. Xmodem:这种古老的传输协议速度较慢,但由 ...
- secureCRT简单上传、下载文件记录
secureCRT简单上传.下载文件记录: 1)sz下载 -y 覆盖 2)rz上传 -y 覆盖 3)以上两个命令属于安装时包含在“Dial-up Networking Support"组中 ...
- 每天一个linux命令(26)--用SecureCRT来上传和下载文件
用SSH管理Linux 服务器时经常需要远程与本地之间交互文件,而直接使用 SecureCRT 自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmod ...
- 每天一个linux命令(26):用SecureCRT来上传和下载文件(转载自竹子)
用SSH管理linux服务器时经常需要远程与本地之间交互文件.而直接用SecureCRT自带的上传下载功能无疑是最方便的,SecureCRT下的文件传输协议有ASCII.Xmodem.Zmodem. ...
随机推荐
- jquery动态创建元素 div元素随垂直滚动条位置变化置顶显示
刚打开页面效果 拖动滑动条之后效果 页面代码 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" & ...
- 拒绝了对对象 'sp_OACreate' (数据库 'mssqlsystemresource',架构 'sys')的 EXECUTE 权限。
执行一个存储过程, 由于里面使用到了一些 --创建对象 EXEC sp_OACreate 'VBScript.RegExp', @objRegex OUT --设置属性 EXEC sp_OASe ...
- 1: 介绍Prism5.0 Introduction to the Prism Library 5.0 for WPF(英汉对照版)
Prism provides guidance designed to help you more easily design and build rich, flexible, and easy- ...
- 各排序算法的Java实现及简单分析
一,直接插入排序 //直接插入排序的算法时间复杂度分析: //如果输入为正序,则每次比较一次就可以找到元素最终位置,复杂度为O(n) //如果输入为反序,则每次要比较i个元素,复杂度为O(n2) // ...
- ClassPathXmlApplicationContext类
org.springframework.context.support Class ClassPathXmlApplicationContext java.lang.Objectorg.springf ...
- New Concept English three(11)
Customs Officers are quite tolerant these days, but they can still stop you when you are going throu ...
- Linux libusb 安装及简单使用
Linux libusb 安装及简单使用 一.参考文档: . libusb1 fails do_configure task with “udev support requested but libu ...
- 正确的使用margin:0 auto与body{text-align:center;}实现元素居中(转)
body{text-align:center}与margin:0 auto的异同? text-align是用于设置或对象中文本的对齐方式.一般情况下我们设置文本对齐方式的时候需要用此属性进行设置 我们 ...
- Docker部署IPython
本文的部署环境是Ubuntu 14.04 Docker Docker 详细概念可以去search,简单来说就是把应用打包到一个容器里的轻量级系统虚拟化服务 IPython Notebook IPyth ...
- Servlet传统配置方式和Servlet3.0使用注解的方式
一.Servlet的传统配置方式 在JavaWeb开发中, 每次编写一个Servlet都需要在web.xml文件中进行配置,如下所示: <servlet> <servlet-name ...