DotNetCore Mvc文件上传功能
FileUploadController 代码,使用了IFormFile,并且把文件保存到本地。
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Web.Filters;
namespace Web.Controllers
{
[ApiException]
[Route("api/fileUpload")]
public class FileUploadController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost("UploadFile")]
public async Task<ActionResult> UploadFile(IFormFile photo)
{
if (photo == null || photo.Length == 0)
return Content("No file selected for upload.");
var fileFolder = Path.Combine("", "wwwroot/static/back.png");
using (var stream = new FileStream(fileFolder, FileMode.Create))
{
await photo.CopyToAsync(stream);
}
return Ok();
}
}
}
前端HTML代码可以直接copy到cshtml文件中使用,逻辑也比较容易理解:
<div id="form-background" style="padding:10px 10px 10px 10px;">
<h4>请选择需要上传的图片:</h4>
<hr />
<div class="row">
<form id="uploadform" name="uploadform" enctype="multipart/form-data" method="post">
<div class="form-group">
<input type="file" name="photo" id="photo" value="" placeholder="首页背景图片">
<br />
<input type="button" class="form-control" onclick="postData();" value="上传" name="" style="width:100px;height:30px;">
</div>
</form>
</div>
</div>
脚本使用了JQuery
<script type="text/javascript">
function postData() {
var formData = new FormData();
formData.append("photo", $("#photo")[0].files[0]);
$.ajax({
url: '/api/fileupload/uploadFile',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (res) {
console.log(res);
alert("上传成功!");
},
error: function () {
alert("上传失败!");
}
})
}
</script>
值得注意的是,前端代码中的文件名photo需要和后端一致
//前端
formData.append("photo", $("#photo")[0].files[0]);
//后端
public async Task<ActionResult> UploadFile(IFormFile photo)
以上实现的是单文件上传的功能.