我有一个我使用ajax提交的文件,但在服务器中我没有收到任何内容。
let file = document.getElementById('file').files[0];
我没有做ajax电话。
axios.post('http://localhost:5000/File/Create', file)
在我的.Net Core中,我期待着这一点。
[HttpPost]
public IActionResult Create([FromBody] IFormFile file)
{
return Ok();
}
这不起作用。我担心我的数据类型是错误的。
答案 0 :(得分:1)
不幸的是,您的问题已经简要描述,但假设其他所有内容都已在您的客户端和服务上正确配置,
我认为您的主要问题是,您发送的数据遗失key: 'file'
,导致file
收到null
。所以,这必须奏效:
axios.post
(
'http://localhost:5000/File/Create',
{
file: file
}
)
希望这有帮助。
答案 1 :(得分:0)
我不确定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中有一个Create action方法,它接收该文件并将其保存到您的app根目录中的某个目录。
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" });
}
}