WCF webHttpBinding协议上传接收文件
2024-10-01 03:43:00
一般情况下wcf用webHttpBinding协议最多的场景就是前后端Json交互,会比较轻量级。
接收上传的文件也可以,不过要自己解析处理。
前端HTML很简单:
<input type="file" id="excel"/>
<div class="btn btn-primary" ng-click="upFile()">上传文件</div>
前端JS也很简单:
$scope.upFile = function () {
var form = new FormData();
var file = document.getElementById("excel").files[0];
form.append('file', file);
$http.post('/SvcWms/InDepot/UpFile', form).then(function (data) {
if(data.data.State === 1){
console.log('upload success');
}
});
};
后台接口定义:
[WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
DtoResponse<bool> UpFile(Stream file);
接口实现:
public class DtoResponse<T>
{
public int State { get; set; } = ;
public string Msg { get; set; }
public T Data { get; set; }
} public DtoResponse<bool> UpFile(Stream file)
{
using (MemoryStream ms = new MemoryStream())
{
file.CopyTo(ms);
ms.Position = ;
using (StreamReader sr = new StreamReader(ms))
{
int firstLineLen = Encoding.UTF8.GetBytes(sr.ReadLine()??"").Length;
var position = firstLineLen + ;
var line = sr.ReadLine();
var filename = DateTime.Now.ToString("yyMMdd.HHmmss."); if(!string.IsNullOrEmpty(line)) {
int idx = line.IndexOf("filename", StringComparison.CurrentCultureIgnoreCase);
filename += line.Substring(idx + ).Replace("\"", "");
} while (line != null)
{
// 特别是第二行含文件名称,可能含中文,所以不能直接用line.Length
// 因为line.Length是字符个数,不是字节个数
position += Encoding.UTF8.GetBytes(line).Length + ;
if (line == "")
break;
line = sr.ReadLine();
}
ms.Position = position;
ms.SetLength(ms.Length - (firstLineLen + )); var uploadStream = new MemoryStream();
ms.CopyTo(uploadStream);
uploadStream.Position = ; File.WriteAllBytes($"d:\\{filename}", uploadStream.ToArray());
}
}
return new DtoResponse<bool>() {State = };
}
最新文章
- Spring 02多种注入方式和注解实现DI
- java的栈图形演示
- 【Flask】Flask快速玩框架
- STAF自动化测试框架
- git基础知识总结
- BZOJ1520 [POI2006]Szk-Schools
- Pull解析xml
- 暑假集训(1)第一弹 -----士兵队列训练问题(Hdu1276)
- Java中4种权限的理解
- JS实现日历控件选择后自动填充
- robot_framewok自动化测试
- linux tcp中time_wait
- radhat6.6上安装oracle12c RAC (二)
- js 实现操作浏览器或者元素的全屏与退出全屏功能
- chat.css
- python练习题-day4
- PHP 时间函数time、date和microtime的区别
- 本地计算机上的OracleDBConsoleorcl服务启动后停止
- 关于Java中语句符号及格式的理解
- Mysql 学习之 SQL的执行顺序
热门文章
- oracle 11g Enterprise Manager配置失败
- Asp.net MVC5 返回json数据忽略序列化属性
- OpenLayers在地图上显示统计图,饼图线状图柱状图,修复统计图跳动的问题
- c# 将一个长耗时任务改成task
- 《JavaScript高级程序设计》3.7 函数
- 异常测试之Socket网络异常
- BroadcastReceive的使用
- elasticsearch Geo Bounding Box Query
- Found an unexpected Mach-O header code: 0x72613c21
- POJ 1270