[英]How to upload file with JQuery to MVC VNext webserver?
尝试使用input type="file"
, FormData
, $.post()
$.ajaxSetup({processData:false,contentType:false});
$("input[type=file]").change(function() {
var data = new FormData(); data.append("file", this.files[0]);
$.post("/path/to/server", data)
});
或者,将文件转换为JSON
对象使用AJAX,PHP和jQuery上传多个图像
将输入文件标签添加到您的视图。
<form asp-action="Index" asp-controller="Home">
<input type="file" id="logo" name="logo" />
<input type="submit" id="btnSave" />
</form>
我们将添加一些JavaScript来监听Submit Button事件并通过ajax发送数据。
@section Scripts
{
<script>
$(function () {
$("#btnSave").click(function (e) {
e.preventDefault();
var fdata = new FormData();
var fileInput = $('#logo')[0];
var file = fileInput.files[0];
fdata.append("logo", file);
$.ajax({
type: 'post',
url: "@Url.Action("SaveFile","Home")",
data: fdata,
processData: false,
contentType: false,
}).done(function (result) {
// do something with the result now
console.log(result);
});
});
});
</script>
}
并且您应该有一个操作方法来接受文件发布
public class HomeController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public HomeController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
[HttpPost]
public IActionResult Index(IFormFile logo)
{
if (logo != null)
{
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads, GetUniqueFileName(logo.FileName));
logo.CopyTo(new FileStream(filePath, FileMode.Create));
}
// to do : Return something
return RedirectToAction("Index","Home");
}
private string GetUniqueFileName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_"
+ Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
}
这会将文件保存到应用程序wwwwroot目录内的uploads文件夹中,并使用Guids生成一个随机文件名(以防止覆盖同名文件)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.