C#:使⽤ajax异步请求实现⽂件上传与下载功能。---项⽬框架
API+MVC
1.⾸先使⽤VS创建WebAPI项⽬
(这⾥有个帮助类,将此帮助类复制到项⽬⾥,有兴趣可以学着写)
//⽂件上传下载,导⼊导出辅助类
public class APIFileHelp
{
  //此为限制⽂件格式
  public string[] ExtentsfileName = new string[] { ".doc", ".xls", ".png", ".jpg" };
  //Upload为⾃定义的⽂件夹,在项⽬中创建
  public string UrlPath = "/Upload/";
  //响应对象,使⽤前先赋值
  public HttpResponse Response = HttpContext.Current.Response;
  public HttpRequest Request = HttpContext.Current.Request;
  //⽂件下载
  //downFileName下载后保存名,sourceFileName服务器端物理路径
  public void DownLoad(string downFileName, string sourceFileName)
  {
    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();
    }   
  }
//⽂件上传操作
public FileResult UpLoad()
{
//保存⽂件名
string name = "";
if (Request.Files.Count > 0)
{
string FileUrlResult = "";
foreach (string fn in Request.Files)
{
var file = Request.Files[fn];
name = file.FileName.ToString();
var extenfilename = Path.GetExtension(file.FileName);
//判断路径是否存在
string path = HttpContext.Current.Server.MapPath(UrlPath);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (ExtentsfileName.Contains(extenfilename.ToLower()))
{
string urlfile = UrlPath + DateTime.Now.ToFileTime() + extenfilename;
mvc实例
string filepath = HttpContext.Current.Server.MapPath(urlfile);
file.SaveAs(filepath);
FileUrlResult += urlfile + ";";
}
//格式不正确
else
{
  //实例化结果类
return new FileResult() { Code = -1, Msg = "只允许上传指定格式⽂件" + string.Join(",", ExtentsfileName), Url = "" };
}
}
//上传成功
return new FileResult() { Code = 0, Name = name, Msg = "上传成功", Url = FileUrlResult };
}
//上传失败
else
{
return new FileResult() { Code = -1, Msg = "不能上传空⽂件", Url = "" };
}
}
}
//结果类
public class FileResult
{
public int Code { get; set; }  //结果
public string Msg { get; set; }  //提⽰信息
public string Url { get; set; }  //地址
public string Name { get; set; }  //⽂件名
}
//控制器端
public class FileOperationController : ApiController
{
//实例化帮助类
APIFileHelp help = new APIFileHelp();
[HttpGet]
public void DownLoad(string Url)
{
string filePath = HttpContext.Current.Server.MapPath(Url);
FileInfo fi = new FileInfo(filePath);
help.DownLoad(fi.Name, fi.FullName);
}
//⽂件上传
[HttpPost]
public FileResult UpLoad()
{
return help.UpLoad();
}
}
//⽂件上传、下载: MVC端
//⽂件下载
//API地址+参数+⾃⼰定义的⽂件名+⽂件Url
<a href = "localhost:44370/api/FileOperation/DownLoad?Url=/FileUpload/132211303318715030.xls" > 下载 </ a >
<input type = "file" id="f1" />
<input type = "button" value="aa" onclick="ff()"/>
<script>
function ff()
  {
var formData = new FormData();
var file = ElementById("f1").files[0];
formData.append("fileInfo", file);
$.ajax({
     url: "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>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。