MVC利用表单上传下载 :
上传控制器:
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
//upload是自己建的文件夹名称
方法一:
//file.SaveAs(Server.MapPath("~/upload") + file.FileName);
//return Content($"{file.FileName}已上传");
//return 1;
方法二:
var fileName = file.FileName;
//文件保存路径
var filePath = Server.MapPath(string.Format("~/{0}", "upload"));
//路径名+文件名
file.SaveAs(Path.Combine(filePath, fileName));
return Content($"{fileName}上传成功");
//return 1;
}
上传视图:
<form action="/Default/Index" method="post" enctype="multipart/form-data"> <input type="file" name="file" />
<input id="submit1" type="submit" value="上传" />
<input id="submit1" type="submit" value="上传" />
</form>
下载控制器
public ActionResult DownLoad(string filename)
{
//下载用到的路径+文件名
string filepath = Server.MapPath(string.Format("~/{0}/{1}", "upload", filename));
//利用文件流打开或创建文件夹
FileStream file = new FileStream(filepath, FileMode.Append);
//执行下载
return File(file,"text/plain", filename);
{
//下载用到的路径+文件名
string filepath = Server.MapPath(string.Format("~/{0}/{1}", "upload", filename));
//利用文件流打开或创建文件夹
FileStream file = new FileStream(filepath, FileMode.Append);
//执行下载
return File(file,"text/plain", filename);
}
下载视图
<a href="@Url.Action("DownLoad","Default",new { filename="a1.jpg"})">下载</a>MVC的异步上传、下载
上传:(控制器同上)
<input type = "file" id="f1" />
<input type = "button" value="aa" onclick="upload()"/>
<input type = "button" value="aa" onclick="upload()"/>
< script >
function upload()
{
var formData = new FormData();
var file = document.getElementById("f1").files[0];
formData.append("fileInfo", file);
$.ajax({
url: "",
type: "POST",
data: formData,
contentType: false,//必须false才会自动加上正确的Content-Type
processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
success: function(d) {
if (d==1){
function upload()
{
var formData = new FormData();
var file = document.getElementById("f1").files[0];
formData.append("fileInfo", file);
$.ajax({
url: "",
type: "POST",
data: formData,
contentType: false,//必须false才会自动加上正确的Content-Type
processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
success: function(d) {
if (d==1){
alert('上传成功')
}
else{
}
else{
alert('上传失败')
}
});
}
}
});
}
</script>