asp.net如何实现文件上传
发布时间:2021-07-27 12:46:58
来源:亿速云
阅读:72
作者:小新
这篇文章主要介绍asp.net如何实现文件上传,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
Controller:public class PictureController : Controller
{
private IHostingEnvironment hostingEnv;
public PictureController(IHostingEnvironment env)
{
this.hostingEnv = env;
}
// GET: //
public IActionResult Index()
{
return View();
}
public IActionResult UploadFiles()
{
return View();
}
[HttpPost]
public IActionResult UploadFiles(IList files)
{
long size = 0;
foreach (var file in files)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
//这个hostingEnv.WebRootPath就是要存的地址可以改下
filename = hostingEnv.WebRootPath + $@"\{filename}";
size += file.Length;
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
}
ViewBag.Message = $"{files.Count} file(s) /{ size}bytes uploaded successfully!";
return View();
}
}
view:
asp-controller="Picture"
method="post"
enctype="multipart/form-data">
文件是上传到wwwroot目录文件下的,这我也看不太懂还在学习,欢迎大家交流~~
----------------------------------------------------------------------------------------------------------
下面是jquery ajax方式上传的
post方式的action的z参数没用 因为只有一个post方式的会404错误所以又加了一个get的action
Controller:public IActionResult UploadFilesAjax()
{
return View();
}
[HttpPost]
public IActionResult UploadFilesAjax(string z)
{
long size = 0;
var files = Request.Form.Files;
foreach (var file in files)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
filename = @"C:\Users\lg.HL\Desktop" + $@"\{filename}";
size += file.Length;
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
}
string message = $"{files.Count} file(s) / { size}bytes uploaded successfully!";
return Json(message);
}
view
name="files" multiple />
id="upload"
value="Upload Selected Files" />
jquery
$(document).ready(function () {
$("#upload").click(function (evt) {
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i
data.append(files[i].name, files[i]);
}
$.ajax({
type: "POST",
url: "/Picture/UploadFilesAjax",
contentType: false,
processData: false,
data: data,
success: function (message) {
alert(message);
},
error: function () {
alert("There was error uploading files!");
}
});
});
});
以上是“asp.net如何实现文件上传”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!