C#MVC通过AJAX调用API方法进行上传下载
//这是写的一个类,具体是上传图片的上传和下载
public class FileResult
{
public int Code { get; set; }
public string Msg { get; set; }
public string Url { get; set; }
}
//首先在api方法内新建一个控制器
//控制器内写关于上传和下载的具体代码
// 允许上传的文件扩展名
public string[] ExtentsfileName = new string[] { ".doc", ".xls", ".png",".jpg" };
public string[] ExtentsfileName = new string[] { ".doc", ".xls", ".png",".jpg" };
public string UrlPath = "/Upload/";
//下载
[HttpGet]
public void DownLoad(string Url)
{
string filePath = HttpContext.Current.Server.MapPath(Url);
FileInfo fi = new FileInfo(filePath);
if (File.Exists(filePath))
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.Buffer = true;
response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fi.Name));
response.Charset = "GB2312";
response.ContentEncoding = Encoding.GetEncoding("GB2312");
response.ContentType = MimeMapping.GetMimeMapping(fi.Name);
response.WriteFile(filePath);
response.Flush();
response.Close();
}
}
[HttpGet]
public void DownLoad(string Url)
{
string filePath = HttpContext.Current.Server.MapPath(Url);
FileInfo fi = new FileInfo(filePath);
if (File.Exists(filePath))
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.Buffer = true;
response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fi.Name));
response.Charset = "GB2312";
response.ContentEncoding = Encoding.GetEncoding("GB2312");
response.ContentType = MimeMapping.GetMimeMapping(fi.Name);
response.WriteFile(filePath);
response.Flush();
response.Close();
}
}
//上传
[HttpPost]
public FileResult UpLoad()
{
var request = HttpContext.Current.Request;
if (request.Files.Count > 0)
{
var file = request.Files[0];
var extenfilename = Path.GetExtension(file.FileName);
[HttpPost]
public FileResult UpLoad()
{
var request = HttpContext.Current.Request;
if (request.Files.Count > 0)
{
var file = request.Files[0];
var extenfilename = Path.GetExtension(file.FileName);
string path = HttpContext.Current.Server.MapPath(UrlPath);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (ExtentsfileName.Contains(extenfilename.ToLower()))
{
string urlfile = UrlPath + DateTime.Now.ToFileTime() + extenfilename;
string filepath = HttpContext.Current.Server.MapPath(urlfile);
file.SaveAs(filepath);
return new FileResult() { Code = 0, Msg = "上传成功", Url = urlfile };
}
else
{
return new FileResult() { Code = -1, Msg = "只允许上传指定格式文件"+string.Join(",",ExtentsfileName), Url = "" };
}
}
else
{
return new FileResult() { Code = -1, Msg = "不能上传空文件", Url = "" };
}
}
}
{
string urlfile = UrlPath + DateTime.Now.ToFileTime() + extenfilename;
string filepath = HttpContext.Current.Server.MapPath(urlfile);
file.SaveAs(filepath);
return new FileResult() { Code = 0, Msg = "上传成功", Url = urlfile };
}
else
{
return new FileResult() { Code = -1, Msg = "只允许上传指定格式文件"+string.Join(",",ExtentsfileName), Url = "" };
}
}
else
{
return new FileResult() { Code = -1, Msg = "不能上传空文件", Url = "" };
}
}
}
//写完api方法之后写mvc前台
<input type = "file" id="f1" />
<input type = "button" value="aa" onclick="ff()"/>
<input type = "button" value="aa" onclick="ff()"/>
< script >
function ff()
{
var formData = new FormData();
var file = document.getElementById("f1").files[0];
formData.append("fileInfo", file);
$.ajax({
url: "https://localhost:44370/api/FileOperation/UpLoad",
type: "POST",
data: formData,
contentType: false,//必须false才会自动加上正确的Content-Type
processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
success: function(data) {
if (data.Code < 0)
alert(data.Msg)
else
alert(data.Url)
},
error: function(data) {
alert("上传失败!");
}
});
}
function ff()
{
var formData = new FormData();
var file = document.getElementById("f1").files[0];
formData.append("fileInfo", file);
$.ajax({
url: "https://localhost:44370/api/FileOperation/UpLoad",
type: "POST",
data: formData,
contentType: false,//必须false才会自动加上正确的Content-Type
processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
success: function(data) {
if (data.Code < 0)
alert(data.Msg)
else
alert(data.Url)
},
error: function(data) {
alert("上传失败!");
}
});
}
</script>
<a href = "https://localhost:44370/api/FileOperation/DownLoad?Url=/FileUpload/132211303318715030.xls" > 下载 </ a >
//ps记住要在api先加上跨域文件,不然api的方法会传不到mvc,本人经常忘记加跨域文件