webuploader.js跨域访问会发送两次请求,第一次是options请求,判断是否有权限访问,成功则再次发送Post请求,
前端代码,
function addUploader(cid, hid) {
var $wordUpload = $('#FilePath_' + cid + '_' + hid).diyUpload({
url: 'http://192.168.3.138:5088/Upload/CourseVideoUpload/?limitType=' + uploadExtensions + '&courseId=' + courseID + '&hid=' + hid,
auto: true, //自动上传
success: function (data) {
if (hid > 0) {
//编辑时保存到隐藏域
$("#file_" + cid + "_" + hid).val(data.data);
} else {
//新增时保存到
documentPath = data.data;
}
if ($('#FilePathUl_' + cid + '_' + hid + ' li').length > 2) {
var li = $('#FilePathUl_' + cid + '_' + hid + ' li:eq(1)');
var id = $(li).prop("id");
var fileid = id.substring(id.length - 9);
li.remove();
$wordUpload.removeFile(fileid);
}
},
error: function (err) { },
buttonText: '',
accept: {
extensions: uploadExtensions,
mimeTypes: uploadMimeTypes
},
thumb: {
width: 120,
height: 90,
allowMagnify: true,
crop: true
},
chunked: false,//是否开启分片上传
chunkSize: 1024 * 1024 * 1024, //分片大小
fileSizeLimit: 1024 * 1024 * 1024,
fileSingleSizeLimit: 1024 * 1024 * 512//512m
});
}
然后请求的项目里面配置可跨域访问,在web.config里面的system.webServer中添加下面的代码,据说还有其他更安全的方式,没有研究
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
然后是MVC控制器的action,前端会发送两次请求,还是不一样的请求,所以这个action既能options访问,也能post访问, [AcceptVerbs(“OPTIONS”, “POST”)]
/// <summary>
/// 课程视频上传
/// </summary>
/// <param name="fileUsedType"></param>
/// <param name="contentType"></param>
/// <returns></returns>
[AcceptVerbs("OPTIONS", "POST")]
public ActionResult CourseVideoUpload(string fileUsedType, string contentType, string courseId, string hid, string limitType = "")
{
if (Request.HttpMethod.Equals("OPTIONS")) {
return Content(JsonHelper.ToJson(new AjaxResult()
{
state = ResultType.success,
message = "成功",
data = null
}));
}
//创建当天的目录
string folderSrc = System.Configuration.ConfigurationManager.AppSettings["VideoPath"] + "/video/course" + courseId + "/hours" + hid + "/";
//判断文件是否存在
if (!Directory.Exists(folderSrc))
{
Directory.CreateDirectory(folderSrc);
}
//上传的文件
var file = Request.Files[0];
//判断文件后缀名
var fileExt = Path.GetExtension(file.FileName).Substring(1).ToLower();
if (!limitType.Contains(fileExt))
{
return Content(JsonHelper.ToJson(new AjaxResult()
{
state = ResultType.error,
message = "不支持该类型文件"
}));
}
string fileName = folderSrc + hid + "." + fileExt;//
//用绝对路径
//var resultPath = fileName;
file.SaveAs(fileName);
var result = fileName;
return Content(JsonHelper.ToJson(new AjaxResult()
{
state = ResultType.success,
message = "成功",
data = fileName
}));
}
public bool VerifyFileExt(string fileExt, string extType)
{
return (extType.Contains(fileExt));
}
就这样,觉得有用的点个赞吧