900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > webapi实现AJAX多文件上传 AJAX调用webapi上传图片或文件

webapi实现AJAX多文件上传 AJAX调用webapi上传图片或文件

时间:2020-11-15 05:07:51

相关推荐

webapi实现AJAX多文件上传 AJAX调用webapi上传图片或文件

AJAX调用webapi上传图片或文件,并返回刚上传的文件名。废话不多说直接贴代码吧

html相关:html>

Title

functiondoUpload(){

varformData=newFormData($("#uploadForm")[0]);

$.ajax({

url:'/api/upload',

type:'post',

data:formData,

async:false,

cache:false,

contentType:false,

processData:false,

success:function(returndata){

alert(returndata);

},

error:function(returndata){

alert("报错了");

console.log(returndata);

}

});

}

无刷新测试:

上传文件:

webapi相关:publicasyncTaskPost()

{

if(!Request.Content.IsMimeMultipartContent())

{

thrownewHttpResponseException(HttpStatusCode.UnsupportedMediaType);

}

stringuploadFolderPath=HostingEnvironment.MapPath("~/Upload");

//如果路径不存在,创建路径

if(!Directory.Exists(uploadFolderPath))

Directory.CreateDirectory(uploadFolderPath);

stringguid=Guid.NewGuid().ToString().Replace("-","");

Listfiles=newList();

varprovider=newWithExtensionMultipartFormDataStreamProvider(uploadFolderPath,guid);

try

{

//Readtheformdata.

awaitRequest.Content.ReadAsMultipartAsync(provider);

//Thisillustrateshowtogetthefilenames.

foreach(varfileinprovider.FileData)

{//接收文件

files.Add(Path.GetFileName(file.LocalFileName));

}

}

catch

{

throw;

}

returnstring.Join(",",files);

}

其中的WithExtensionMultipartFormDataStreamProvider类:publicclassWithExtensionMultipartFormDataStreamProvider:MultipartFormDataStreamProvider

{

publicstringguid{get;set;}

publicWithExtensionMultipartFormDataStreamProvider(stringrootPath,stringguidStr)

:base(rootPath)

{

guid=guidStr;

}

publicoverridestringGetLocalFileName(.Http.Headers.HttpContentHeadersheaders)

{

stringextension=!string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName)?Path.GetExtension(GetValidFileName(headers.ContentDisposition.FileName)):"";

returnguid+extension;

}

privatestringGetValidFileName(stringfilePath)

{

char[]invalids=System.IO.Path.GetInvalidFileNameChars();

returnString.Join("_",filePath.Split(invalids,StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');

}

}

效果如下:

图片与文件被成功上传了:

欢迎加群讨论技术,群号:677373950

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。