Api服务代码一:

        /// <summary>
/// 服务器接收接口
/// </summary>
[HttpPost]
[Route("ReceiveFile")]
public HttpResponseMessage ReceiveFile()
{
string result = string.Empty;
ArrayList list = new ArrayList();
try
{
Stream postStream = HttpContext.Current.Request.InputStream;
byte[] b = new byte[postStream.Length]; string postFileName = DNTRequest.GetString("fileName");
if (string.IsNullOrEmpty(postFileName) && HttpContext.Current.Request["fileName"] != null)
{
postFileName = HttpContext.Current.Request["fileName"];
}
string fileExtension = Path.GetExtension(postFileName);
string dirName = "other";
if (!string.IsNullOrEmpty(fileExtension))
{
dirName = fileExtension.Substring(fileExtension.LastIndexOf(".") + );
}
string dir = "/_temp/file/" + dirName + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff");
fileName += fileExtension;
string filePath = HttpContext.Current.Server.MapPath(dir);
string saveFilePath = Path.Combine(filePath, fileName);
string dirPath = dir + fileName;
list.Add(dirPath); if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
} FileStream fs = new FileStream(saveFilePath, FileMode.Create);
byte[] new_b = new byte[];
const int rbuffer = ; while (postStream.Read(new_b, , rbuffer) != )
{
fs.Write(new_b, , rbuffer);
}
postStream.Close();
fs.Close();
fs.Dispose(); if (list.Count > )
{
result = DNTRequest.GetResultJson(true, "success", string.Join(",", list.ToArray()));
}
}
catch (Exception ex)
{
result = DNTRequest.GetResultJson(false, ex.Message, null);
}
HttpResponseMessage responseMessage = new HttpResponseMessage { Content = new StringContent(result, Encoding.GetEncoding("UTF-8"), "text/plain") };
return responseMessage;
}

Api服务代码二:

        [HttpPost]
[Route("ReceiveFileTest")]
public HttpResponseMessage ReceiveFileTest()
{
string result = string.Empty;
var request = HttpContext.Current.Request;
try
{
if (request.Files.Count > )
{
var fileNameList = new List<string>();
string dirName = "other";
foreach (string f in request.Files)
{
var file = request.Files[f]; string fileExtension = Path.GetExtension(file.FileName).ToLower();
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff");
fileName += fileExtension;
if (!string.IsNullOrEmpty(fileExtension))
{
dirName = fileExtension.Substring(fileExtension.LastIndexOf(".") + );
}
string dir = "/_temp/file/" + dirName + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
string filePath = HttpContext.Current.Server.MapPath(dir);
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
string fileSavePath = Path.Combine(filePath, fileName); Stream postStream = file.InputStream;
//
FileStream fs = new FileStream(fileSavePath, FileMode.Create);
byte[] new_b = new byte[];
const int rbuffer = ; while (postStream.Read(new_b, , rbuffer) != )
{
fs.Write(new_b, , rbuffer);
}
postStream.Close();
fs.Close();
fs.Dispose(); string dirPath = dir + fileName;
fileNameList.Add(dirPath);
fileNameList.Add(fileName);
} result = DNTRequest.GetResultJson(true, string.Format("{0}:{1}", HttpStatusCode.OK, string.Join(",", fileNameList.ToArray())), null);
}
else
{
result = DNTRequest.GetResultJson(false, "请选择上传的文件", null);
}
}
catch (Exception ex)
{
result = DNTRequest.GetResultJson(false, ex.Message, null);
}
HttpResponseMessage responseMessage = new HttpResponseMessage { Content = new StringContent(result, Encoding.GetEncoding("UTF-8"), "text/plain") };
return responseMessage;
}

Ajax提交file代码,调用Api代码一的Script:

此方法后端Api代码一中始终获取不到文件名,所以我在Ajax的url中加了?fileName=fileObj.name,这样调试能走通。为什么Ajax提交时不能获取到文件名,我还在研究。

<script>

        $("#inpSubmit").click(function () {
//var fileObj = new FormData($("#importModel")[0]);
var fileObj = document.getElementById("inpFileControl").files[0];
if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
alert("请选择文件");
return;
}
//console.log(fileObj); var formFile = new FormData();
formFile.append("fileName", fileObj.name);
formFile.append("file", fileObj);
//console.log(JSON.stringify(formFile)); //var paramters = {};
//paramters.timestamp = new Date().getTime();
//paramters.fileName = fileObj.name;
//paramters.file = fileObj;
//console.log(JSON.stringify(paramters)); $.ajax({
type: "post",
url: "http://localhost:19420/Api/ReceiveFile?fileName=" + fileObj.name,
dataType: "json",
//contentType: false,
processData: false,//用于对data参数进行序列化处理,默认值是true。默认情况下发送的数据将被转换为对象,如果不希望把File转换,需要设置为false
cache: false,
data: fileObj,
success: function (json) {
if (json.result) {
$("#inpFileUrl").val(json.data);
console.log(json.data);
}
else {
alert(json.msg);
}
},
error: function (ret) {
console.log(ret.responseText);
}
});
return false;
});
</script>

Ajax提交file代码,调用Api代码一的Html:

<form>
<fieldset>
<legend>Ajax提交到远程服务器Api</legend>
<div class="form-group">
<label class="col-sm-2 control-label" for="ds_host">选择文件</label>
<div class="col-sm-4">
<input class="form-control" id="inpFileUrl" name="inpFileUrl" type="text" placeholder="上传后返回地址" />
</div>
<div class="col-sm-4">
<input type="file" id="inpFileControl" name="file" />
</div>
<div class="col-sm-2">
<input id="inpSubmit" name="inpSubmit" type="button" value="提交" />
</div>
</div>
</fieldset>
</form>

Form表单提交Post到远程Api代码二中,这个很顺利。下边是Html

<form action="http://localhost:19420/Api/ReceiveFileTest" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Form表单提交到远程服务器Api</legend>
<div class="form-group">
<label class="col-sm-2 control-label" for="ds_host">选择文件</label>
<div class="col-sm-4">
<input class="form-control" id="inpFileUrl2" name="inpFileUrl2" type="text" placeholder="上传后返回地址" />
</div>
<div class="col-sm-4">
<input type="file" name="file" />
</div>
<div class="col-sm-2">
<input type="submit" value="提交" />
</div>
</div>
</fieldset>
</form>

Api服务部署时需要考虑到客户端提交file时有跨域问题,快捷方法是在IIS中设置Access-Control-Allow-Origin:*,但这样做有安全问题。

网站上传文件大小默认4M,所以网站配置文件中需要设置,如下:

  <system.web>
<httpRuntime maxRequestLength="" />
</system.web>

服务器IIS上传文件大小也有限制,也要做设置,如下:

  <system.webServer>
<security>
<requestFiltering>
<!--2G/|500M/-->
<requestLimits maxAllowedContentLength=""/>
</requestFiltering>
</security>
</system.webServer>

以上是我近2天的研究成果,不算完善还需要改进。

Api中使用了三方框架RestSharp,请在解决方案中找NuGet添加。

外部操作类用到的方法有,一:

        /// <summary>
/// 拼装JSON
/// </summary>
static public string GetResultJson(bool result, string msg, Object data)
{
string resultJson = string.Empty;
Hashtable ht = new Hashtable();
try
{
ht.Add("result", result);
ht.Add("msg", msg);
ht.Add("data", data);
}
catch (Exception ex)
{
ht.Add("result", false);
ht.Add("msg", ex.Message);
}
resultJson = Newtonsoft.Json.JsonConvert.SerializeObject(ht);
return resultJson;
}

注意:Html代码中file控件需要有name=“file”属性,否则提交后Api获取不到file对象,如下。

<input type="file" name="file" />

第三种方法是form表单提交调用mvc的control,control在调用Api代码二,这个测试失败,能上传文件,但上传的文件不能打开是损坏的,正在想办法解决。

下边是第三种方法的Html代码:

<form action="/Test/UploadFileTest" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Form表单提交到本地Control</legend>
<div class="form-group">
<label class="col-sm-2 control-label" for="ds_host">选择文件</label>
<div class="col-sm-4">
<input class="form-control" id="inpFileUrl3" name="inpFileUrl3" type="text" placeholder="上传后返回地址" />
</div>
<div class="col-sm-4">
<input type="file" name="file" />
</div>
<div class="col-sm-2">
<input type="submit" value="提交" />
</div>
</div>
</fieldset>
</form>

下边是第三种方法的Control代码:

        [HttpPost]
public ActionResult UploadFileTest()
{
string result = string.Empty; string apiUrl = "http://localhost:19420/Api/ReceiveFileTest";
string contentType = "application/octet-stream"; var files = new List<string>();
foreach (string f in Request.Files)
{
var file = Request.Files[f];
var request = new RestRequest(Method.POST);
request.AlwaysMultipartFormData = true;
//request.AddParameter("fileName", file.FileName);
Stream postStream = file.InputStream;
byte[] b = new byte[postStream.Length];
request.AddFile("file", b, file.FileName, contentType); var restClient = new RestClient { BaseUrl = new Uri(apiUrl) };
string res = string.Empty;
IRestResponse<Object> response = restClient.Execute<Object>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
res = response.Content;
}
else
{
res = string.Format("{0}:{1}", response.StatusCode, response.Content);
}
files.Add(res);
}
if (files.Count > ) {
result = string.Join(",", files.ToArray());
} return Json(result);
}

.Net C#向远程服务器Api上传文件的更多相关文章

  1. 返璞归真 asp.net mvc (11) - asp.net mvc 4.0 新特性之自宿主 Web API, 在 WebForm 中提供 Web API, 通过 Web API 上传文件, .net 4.5 带来的更方便的异步操作

    原文:返璞归真 asp.net mvc (11) - asp.net mvc 4.0 新特性之自宿主 Web API, 在 WebForm 中提供 Web API, 通过 Web API 上传文件, ...

  2. 演示如何通过 web api 上传文件MVC40

    演示如何通过 web api 上传文件WebApiWebFormHost/UploadFileController.cs /* * 通过 web api 上传文件 */ using System; u ...

  3. php 下 html5 XHR2 + FormData + File API 上传文件

    FormData的作用: FormData对象可以帮助我们自动的打包表单数据,通过XMLHttpRequest的send()方法来提交表单.当然FormData也可以动态的append数据.FormD ...

  4. C# Web Api 上传文件

    一. 使用默认方法上传文件: 1.Action: /// <summary> /// 上传文件 使用上传后的默认文件名称 /// 默认名称是BodyPart_XXXXXX,BodyPart ...

  5. 从Linux服务器下载上传文件

    首先要确定好哪两种的连接:Linux常用的有centors和unbantu两种版本,PC端Mac和Windows 如果在两个Linux之间传输,或Linux和Mac之间传输可以使用scp命令,类似于s ...

  6. 1.5 WEB API 上传文件

    1.前提,设置跨域 2.在控制器头添加允许跨域 /// <summary> /// 文件管理口控制器 /// </summary> [EnableCors("*&qu ...

  7. HttpClient 测试web API上传文件实例

    1.使用HttpClient 测试上传文件并且设置header信息: using Lemon.Common; using Newtonsoft.Json; using System; using Sy ...

  8. 前端AngularJS后端ASP.NET Web API上传文件

    本篇体验使用AngularJS向后端ASP.NET API控制器上传文件.    首先服务端: public class FilesController : ApiController { //usi ...

  9. 使用root用户登录到AWS EC2服务器,上传文件到/var/www目录

    关键词 1.aws ec2中上传文件到/var/www目录(使用filezilla) 2.使用root用户登录aws ec2实例 上一篇随笔中记录了在aws ec2实例中部署apache服务器的过程, ...

随机推荐

  1. C++类指针类型的成员变量的浅复制与深复制

    本篇文章旨在阐述C++类的构造,拷贝构造,析构机制,以及指针成员变量指针悬空问题的解决.需要读者有较好的C++基础,熟悉引用,const的相关知识. 引言: 类作为C++语言的一种数据类型,是对C语言 ...

  2. CF529B 【Group Photo 2 (online mirror version)】

    贪心枚举最后方案中最大的h,设为maxh若某个人i的wi与hi均大于maxh,则此方案不可行若某个人恰有一个属性大于maxh,则可确定他是否换属性剩下的人按wi-hi从大到小排序后贪心选择O(nlog ...

  3. es6之yield

    yield 关键字用来暂停和继续一个生成器函数.我们可以在需要的时候控制函数的运行. yield 关键字使生成器函数暂停执行,并返回跟在它后面的表达式的当前值.与return类似,但是可以使用next ...

  4. kafka介绍与搭建(单机版)

    一.kafka介绍 1.1 主要功能 根据官网的介绍,ApacheKafka®是一个分布式流媒体平台,它主要有3种功能: 1:It lets you publish and subscribe to ...

  5. node模拟socket

    什么是Socket?网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket. Socket通信流程 基于net模块实现socket 服务端SocketServer.j ...

  6. 从exp入手分析漏洞

    分析poc和分析exp有一些不一样,因为exp是人为构造后的东西,它会执行一段自定的shellcode.结果是根本不会触发异常或者异常在离触发点十万八千里的地方.这样分析poc的技巧就用不上了(因为无 ...

  7. NSPredicate用法总结(Cocoa框架中的NSPredicate用于查询,原理和用法都类似于SQL中的where,作用相当于数据库的过滤取)

    简述:Cocoa框架中的NSPredicate用于查询,原理和用法都类似于SQL中的where,作用相当于数据库的过滤取. 定义(最常用到的方法): NSPredicate *ca = [NSPred ...

  8. Java学习笔记之:Struts2.0 环境搭建

    一.介绍 Struts2是一个基于MVC设计模式的Web应用框架,它本质上相当于一个servlet,在MVC设计模式中,Struts2作为控制器(Controller)来建立模型与视图的数据交互. 二 ...

  9. 黑马程序员_java基础笔记(06)...集合

    —————————— ASP.Net+Android+IOS开发..Net培训.期待与您交流! —————————— JavaApi(其实就是java给我们提供的已经定义好的对象.工具对象:集合框架) ...

  10. js 参数传递

    最近在读<javascript高级程序设计>时碰到了js传递方式的问题,花费了些时间,不过总算明白了. 数据类型 在 javascript 中数据类型可以分为两类: 基本类型值 primi ...