AngularJs&Jquery与WebApi那点事

发布于 2018-05-06  219 次阅读


首先是跨域问题,两种情况

//这种就是普通的发送请求点数据 不涉及上传文件
//主要是这个postCfg 用的是jquery的$.param方法创建数组或对象的序列化表示
var postCfg = {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (data) {
return data != "" ? $.param(data) : data;
}
};
 $http.post("url", data, postCfg).success(function (e) {
 
 }).error(function (data, status, headers, config) {
 
 });
//这种是在用jquery ajax 上传文件时用到的
//因为上传文件需要有进度条,触发进度条那个事件需要开启async
//一开启async就不知道就似乎又出现那跨域问题了,加上如下代码才好
//在Global.asax中才行,WebConfig里也配置有就是没啥效果
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
"Accept, Content-Type,customHeader");

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
"POST,GET,OPTIONS");

HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
"172800");

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials",
"true");

HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers",
"customHeader");

HttpContext.Current.Response.AddHeader("Content-type",
"application/json");

HttpContext.Current.Response.End();
}
else
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
"Accept, Content-Type,customHeader");

HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers",
"customHeader");

HttpContext.Current.Response.AddHeader("Content-type",
"application/json");

}
}

顺便附上ajax异步上传文件加进度条显示

 $scope.UploadFile = function () {
 var fileObj = document.getElementById("FileUpload").files[0]; // js 获取文件对象
 if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
 alert("请选择图片");
 return;
 }
 var formFile = new FormData();
 formFile.append("file", fileObj); //加入文件对象
 var data = formFile;
 $.ajax({
 url: root.getRoot().url + "/file/upload",
 data: data,
 type: "Post",
 dataType: "json",
 async: true, //异步才能调用 xhr 回掉函数
 cache: false,//上传文件无需缓存
 processData: false,//用于对data参数进行序列化处理 这里必须false
 contentType: false, //必须
 success: function (data) {
 var result = JSON.stringify(data);
 result = JSON.parse(result);
 result = JSON.parse(result);
 if (result.Flag) {
 $scope.imgData.push(result.Data);
 $scope.$apply()
 }
 else {
 alert("上传失败");
 }
 },
 //拿到jQuery产生的 XMLHttpRequest对象,为其增加 progress 事件绑定,然后再返回交给ajax使用
 xhr: function () {
 myXhr = $.ajaxSettings.xhr();
 if (myXhr.upload) { // check if upload property exists
 myXhr.upload.addEventListener('progress', function (e) {
 var loaded = e.loaded; //已经上传大小情况
 var total = e.total; //附件总大小
 var percent = Math.floor(100 * loaded / total); //已经上传的百分比
 if (percent == 100) {
 $("#processBar").css("display", "none");
 }
 else {
 $("#processBar").display("display", "block");
 $("#processBar").css("width", percent + "%");
 $("#processBar").html(percent + "%");
 }

 }, false); // for handling the progress of the upload
 }
 return myXhr;
 },
 })
 }
 <div id="processBar" class="processBar" style="display:none;">
 </div>

然后就是webapi后台接收数据的问题了

注意: ajax中data直接发送json数据过去,接收不到。。。

所以必须用jquery的$.param方法创建数组或对象的序列化表示 在文章开头写有

接收单个参数

直接地址传参就行,多个参数也行,

url?key=value&key1=value1

多个参数时可以新建个Model

public class InfoModel
{
public string MenuId { get; set; }
public int PageSize { get; set; }
public int PageIndex { get; set; }
}

public string GetInfo(InfoModel model)
{

}

 

webapi接收表单文件


public string Upload()
{
var result = new Result<string>();
var files = HttpContext.Current.Request.Files;

//接收表单参数用

// var param = HttpContext.Current.Request.Form["param "];

if (files.Count > 0)
{
// 获取图片文件
HttpPostedFile httpPostedFile = files[0];

//最大文件大小15M
int maxSize = 1024 * 1024 * 15;
if (httpPostedFile.InputStream.Length > maxSize)
{
return null;
}

// 文件扩展名
string fileExtension = Path.GetExtension(httpPostedFile.FileName);
// 图片名称
string fileName = Guid.NewGuid().ToString() + fileExtension;
string path = "/Upload/" + DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/";
var serverPath = HttpContext.Current.Server.MapPath(path);

if (!Directory.Exists(serverPath))
Directory.CreateDirectory(serverPath);
// 图片上传路径
string filePath = Path.Combine(serverPath, fileName);

httpPostedFile.SaveAs(filePath);

string imgPath = ServerUrl + path + fileName;
result.Flag = true;
result.Data = imgPath;
result.Msg = "上传成功";
}
return JsonHelper.ObjectToJson(result);

}

LoneKing