一般情况下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 = };
}