我不確定axios
如何處理上傳。但通常你需要發送包含該文件的FormData。當使用jQuery AJAX發送此表單數據,您需要確保您設置的processData
和contentType
標誌來false
這樣的事會工作
$("#saveBtn").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("Create", "File")",
data: fdata,
processData: false,
contentType: false
}).done(function(result) {
// do something with the result now
console.log(result);
});
});
假設你有FileController創建操作方法該文件將該文件保存到您的應用程序根目錄中的某個目錄中。
public class FileController : Controller
{
private readonly IHostingEnvironment hostingEnvironment;
public FileController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
[HttpPost]
public IActionResult SaveFile(IFormFile logo)
{
if (logo != null)
{
//simply saving to "uploads" directory
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads, logo.FileName);
logo.CopyTo(new FileStream(filePath, FileMode.Create));
return Json(new { status = "success" });
}
return Json(new { status = "error" });
}
}
請顯示發送的數據以及服務器上包含的「文件」。另外,如果不是'AJAX'文章,'axios'是做什麼的? –
查看[示例](https://github.com/mzabriskie/axios/blob/master/examples/upload/index.html)瞭解如何使用axios上傳文件。至少,你需要使用'FormData'。 –
你在客戶端做錯了。看看[這個axios示例如何上傳文件](https://github.com/mzabriskie/axios/blob/master/examples/upload/index.html)。 – poke