这是我的客户端html(我用过ng文件上传)
<button type="file" ngf-select="uploadFileToUrl($file)"
ngf-max-size="100MB">
<!--ngf-max-height="1000"-->
Photo
</button>
这是我的客户端js
$scope.uploadFileToUrl = function (file) {
console.log(file) // Here console prints my file information
alert(file);
var data = new FormData();
data.append('photo', file)
$.ajax({
type: "POST",
url: "http://localhost:22475/api/FileUpload",
contentType: false,
processData: false,
data: data,
success: function (message) {
alert(message);
},
error: function () {
alert("There was error uploading files!");
}
});
}
这是我的服务器端
private IHostingEnvironment hostingEnv ;
public FileUploadController(IHostingEnvironment env)
{
this.hostingEnv = env;
}
[HttpPost]
public async Task<IActionResult> PostProfilePicture(ICollection<IFormFile> files) // Here i get file count 0 on tool tip
{
var uploads = Path.Combine(hostingEnv.WebRootPath, "uploads");
foreach (var file in files)
{
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
return null;
}
这里我得到文件上传错误我通过网络搜索,所有我得到这个代码,但它不工作,任何人都可以帮助,并指出我在这里做错了什么..
答案 0 :(得分:0)
您在URL中调用操作结果名称是'FileUpload',而服务器端操作结果名称是'PostProfilePicture'。您需要在两侧保持相同的名称,或者您可以在服务器端代码
中的httppost上添加路由名称[Route("api/FileUpload")]
[HttpPost]
答案 1 :(得分:0)
我得到了答案
public async Task<IActionResult> Post(ICollection<IFormFile> files)
{
var v = Request.Form.Files[0];
var uploads = Path.Combine(hostingEnv.WebRootPath, "uploads");
using (var fileStream = new FileStream(Path.Combine(uploads, v.FileName), FileMode.Create))
{
await v.CopyToAsync(fileStream);
}
return null;
}
从请求中获取文件并将其上传,Thanku