文件上传:
API内容:
/// <summary>
/// 文件上传
/// </summary>
/// <returns></returns>
[HttpPost]
public int Upload()
{
if (HttpContext.Current.Request.Files.Count > 0)
{
//获取文件
var file = HttpContext.Current.Request.Files[0];
//获取上传文件的扩展名
//首先将文件名按.切割
var temp = file.FileName.Split('.');
//获取扩展名
var extendName = temp[temp.Length - 1];
//获取路径
var path = HttpContext.Current.Server.MapPath("~/Upload/");
//判断路径是否存在
if (Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
//文件重新命名
var name = DateTime.Now.ToFileTime() + "." + extendName;
//保存上传文件
file.SaveAs(Path.Combine(path, name));
//返回结果
return 1;
}
else
{
return 0;
}
}
MVC中视图:
ViewBag.Title = "APIIndex";
}
<input id="F1" type="file" />
<input id="Button1" type="button" value="上传" onclick="upload()" />
var data = new FormData();
//获取文件
var file = document.getElementById("F1").files[0];
//添加数据
data.append("F1", file);
$.ajax({
url: 'http://localhost:44363/api/Default/Upload',
type: 'post',
data: data,
contentType: false,//必须false才会自动加上正确的Content-Type
processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
success: function (d) {
if (d > 0) {
alert("上传成功!");
return;
} else {
alert("上传失败!");
return;
}
}
});
}
</script>
/// 响应对象,使用前先赋值
/// </summary>
public HttpResponse Response = HttpContext.Current.Response;
/// 文件下载
/// </summary>
/// <returns></returns>
[HttpGet]
public void DowdLoad(string Url)
{
FileInfo fs = new FileInfo(filePath);
//获取文件名
string downFileName = fs.Name;
//获取服务器端物理路径
string sourceFileName = fs.FullName;
//判断物理路径是否存在
if (File.Exists(sourceFileName))
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", downFileName));
Response.Charset = "GB2312";
Response.ContentEncoding = Encoding.GetEncoding("GB2312");
Response.ContentType = MimeMapping.GetMimeMapping(downFileName);
Response.WriteFile(sourceFileName);
Response.Flush();
Response.Close();
}
}
MVC视图内容:
<a href = "https://localhost:44370/api/Default/DownLoad?Url=/FileUpload/132211303318715030.xls" > 下载 </ a >