Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/472.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在Asp.Net内核中使用Ajax上传文件_Javascript_C#_Jquery_Asp.net_Ajax - Fatal编程技术网

Javascript 在Asp.Net内核中使用Ajax上传文件

Javascript 在Asp.Net内核中使用Ajax上传文件,javascript,c#,jquery,asp.net,ajax,Javascript,C#,Jquery,Asp.net,Ajax,大家好, 我试图使用ajax将文件从客户端上传到服务器端(asp.NETCore)控制器,但我有一个空值 以下是我的html和javascript代码: <input type="file" id="myfile" class="required" /> <button type="button" class="btn btn-info" onclick="uploadcsvfile()"> <script> function uploadcsvfi

大家好,

我试图使用ajax将文件从客户端上传到服务器端(asp.NETCore)控制器,但我有一个空值

以下是我的html和javascript代码:

<input type="file" id="myfile" class="required" />
<button type="button" class="btn btn-info" onclick="uploadcsvfile()">

<script>
    function uploadcsvfile() {
       var myfile= document.getElementById("myfile");
       var formData = new FormData();

       if (myfile.files.length > 0) {
           for (var i = 0; i < myfile.files.length; i++) {
               formData.append('file-' + i, myfile.files[i]);
           }
       }

       $.ajax({
           url: "/MyController/UploadFile/",
           type: "POST",
           dataType: "json",
           data: formData,
           contentType: false,
           processData: false,
           success: function(data){

           },
           error: function (data) {

           }
        })
    }
</script>

函数uploadcsvfile(){
var myfile=document.getElementById(“myfile”);
var formData=new formData();
如果(myfile.files.length>0){
对于(var i=0;i
这是我使用IFormFile的控制器

public async Task<JsonResult> UploadFile(IFormFile formData)
{
      // do something here
}
public异步任务上传文件(formfile formData)
{
//在这里做点什么
}

提前谢谢你

以下是一种将文件发布到控制器操作的简单方法

查看

var formData = new FormData();
formData.append('file', $('#myfile')[0].files[0]); // myFile is the input type="file" control

var _url = '@Url.Action("UploadFile", "MyController")';

$.ajax({
    url: _url,
    type: 'POST',
    data: formData,
    processData: false,  // tell jQuery not to process the data
    contentType: false,  // tell jQuery not to set contentType
    success: function (result) {
    },
    error: function (jqXHR) {
    },
    complete: function (jqXHR, status) {
    }
});
[HttpPost]
public ActionResult UploadFile(IFormFile file)
{
    List<string> errors = new List<string>(); // added this just to return something

    if (file != null)
    {
        // do something
    }

    return Json(errors, JsonRequestBehavior.AllowGet);   
}
控制器

var formData = new FormData();
formData.append('file', $('#myfile')[0].files[0]); // myFile is the input type="file" control

var _url = '@Url.Action("UploadFile", "MyController")';

$.ajax({
    url: _url,
    type: 'POST',
    data: formData,
    processData: false,  // tell jQuery not to process the data
    contentType: false,  // tell jQuery not to set contentType
    success: function (result) {
    },
    error: function (jqXHR) {
    },
    complete: function (jqXHR, status) {
    }
});
[HttpPost]
public ActionResult UploadFile(IFormFile file)
{
    List<string> errors = new List<string>(); // added this just to return something

    if (file != null)
    {
        // do something
    }

    return Json(errors, JsonRequestBehavior.AllowGet);   
}
[HttpPost]
public ActionResult上载文件(IFormFile文件)
{
List errors=new List();//添加此项只是为了返回某些内容
如果(文件!=null)
{
//做点什么
}
返回Json(错误,JsonRequestBehavior.AllowGet);
}

您只需指定文件输入“name”属性(与ASP.NET控制器中的变量名相同)。 HTML:

对于AJAX请求,您需要在FormData对象中指定适当的名称。

详细解释如下:

浏览器端代码: HTML
服务器端代码:
[HttpPost]
公共异步任务索引(IList文件)
{
foreach(文件中的文件源)
{
string filename=ContentDispositionHeaderValue.Parse(source.ContentDisposition.filename.Trim(“”);
filename=this.EnsureCorrectFilename(文件名);
使用(FileStream output=System.IO.File.Create(this.GetPathAndFilename(filename)))
等待source.CopyToAsync(输出);
}
返回这个.View();
}
私有字符串文件名(字符串文件名)
{
if(filename.Contains(“\\”)
filename=filename.Substring(filename.LastIndexOf(“\\”)+1);
返回文件名;
}
私有字符串GetPathAndFilename(字符串文件名)
{
返回this.hostingEnvironment.WebRootPath+“\\uploads\\”+文件名;
}

使用(.Net Core)的完整工作示例。部分答案采用了上述答案,并修复了编译错误

假设您想要上传文件,那么您将提交带有上传文件的表单

Register.cshtml

由于参数名称不同,正在获取null值。 客户端: 而不是将file-i add fromData设置为与动作方法参数名相同的

formData.append('formData' myfile.files[i]);

上载csv文件时,请添加验证以仅允许csv文件。
当你上传多个文件时 Html:添加多个属性

<input type="file" id="myfile" class="required" multiple />

服务器端:添加

公共异步任务上载文件(列表formData)
{
//在这里做点什么
}

如果您没有使用表单标记,那么添加@Html.AntiForgeryToken()

现在有什么问题?您甚至有没有收到对您的操作方法的调用?服务器是否需要
数据:{formData:formData}
?在
公共异步任务上载文件(formfile formData)中需要什么
formData
?任务的目的是什么?@guest271314如果我将其与大括号一起使用,我会得到null@SaurabhTiwari我可以破坏该方法,但formData的值是null@jsonGPPD你能接受答案吗?我刚刚试过Mohammed Noureldin的答案,这对我有效,哪一个对你有效?内容类型如何et to media?@NevilleNazerane AFAIK jquery将自动为您的ajax请求设置适当的内容类型。我目前正在使用此设置在我的一个项目中上载excel文档。问题是,在Asp.Net Core中,没有HttpPostedFileBase,只有IFormFile。有什么方法可以实现该文件吗?@Jsongpd忘记了这一点。检查更新后的答案。工作正常。在我发送的示例模型中,还包含其他信息,如firstname last name等。公共类模型{public string firstname{get;set;}公共列表附件{get;set;}当我从ajax发送邮件时,我收到了400个状态码。如何发布?@SagarPatil请发布一个关于该问题的新问题,并在此处添加问题的链接作为评论,我将很高兴尽我最大的努力提供帮助。@MohammedNoureldin请在此处找到我的问题您在列出最佳选项方面的创造力。非常漂亮
[HttpPost]
public async Task<IActionResult> Index(IList<IFormFile> files)
{
  foreach (IFormFile source in files)
  {
    string filename = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Trim('"');

    filename = this.EnsureCorrectFilename(filename);

    using (FileStream output = System.IO.File.Create(this.GetPathAndFilename(filename)))
      await source.CopyToAsync(output);
  }

  return this.View();
}

private string EnsureCorrectFilename(string filename)
{
  if (filename.Contains("\\"))
    filename = filename.Substring(filename.LastIndexOf("\\") + 1);

  return filename;
}

private string GetPathAndFilename(string filename)
{
  return this.hostingEnvironment.WebRootPath + "\\uploads\\" + filename;
}
@using UploadFileAjaxPostWebApp.Models.Account

@model RegisterModel

@using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
  <div>
    <label>First Name </label>
    <input type="text" name="FirstName" value="John" />
  </div>
  <div>
    <label>Second Name </label>
    <input type="text" name="SecondName" value="Smith" />
  </div>
  <div>
    <label>Resume</label>
    <input type="file" id="fileUpload1" onchange="uploadFiles('fileUpload1');" />
    <input type="hidden" id="ResumeFileName" name="ResumeFileName" value="@Model.ResumeFileName" />
  </div>

  <div>
    <input type="submit" value="Submit" />
  </div>
}

<script type="text/javascript">

function uploadFiles(inputId) {
    var input = document.getElementById(inputId);
    var files = input.files;
    var formData = new FormData();

    for (var i = 0; i !== files.length; i++) {
        formData.append("files", files[i]);
    }

    $.ajax(
        {
            url: "/account/uploadfiles",
            data: formData,
            processData: false,
            contentType: false,
            type: "POST",
            success: function (data) {
                // Set the property of the Model.
                $("#ResumeFileName").val(data.fileName);
                alert("Files Uploaded! " + data.fileName);
            }
        }
    );
}
</script>
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using UploadFileAjaxPostWebApp.Models.Account;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;

namespace UploadFileAjaxPostWebApp.Controllers
{
  public class AccountController : Controller
  {
    private readonly IWebHostEnvironment _hostEnvironment;

    public AccountController(IWebHostEnvironment hostEnvironment)
    {
        _hostEnvironment = hostEnvironment;
    }

    public IActionResult Register()
    {
        RegisterModel model = new RegisterModel();

        return View(model);
    }

    [HttpPost]
    public IActionResult Register(RegisterModel model)
    {
        // Handle your post action ....
        return View(model);
    }

    [HttpPost]
    public async Task<ActionResult> UploadFiles(IList<IFormFile> files)
    {
        string fileName = null;

        foreach (IFormFile source in files)
        {
            // Get original file name to get the extension from it.
            string orgFileName = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Value;

            // Create a new file name to avoid existing files on the server with the same names.
            fileName = DateTime.Now.ToFileTime() + Path.GetExtension(orgFileName);

            string fullPath = GetFullPathOfFile(fileName);

            // Create the directory.
            Directory.CreateDirectory(Directory.GetParent(fullPath).FullName);

            // Save the file to the server.
            await using FileStream output = System.IO.File.Create(fullPath);
            await source.CopyToAsync(output);
        }

        var response = new { FileName = fileName };

        return Ok(response);
    }

    private string GetFullPathOfFile(string fileName)
    {
        return $"{_hostEnvironment.WebRootPath}\\uploads\\{fileName}";
    }
 }
}
namespace UploadFileAjaxPostWebApp.Models.Account
{
  public class RegisterModel
  {
    public string FirstName { get; set; }

    public string SecondName { get; set; }

    public string ResumeFileName { get; set; }
  }
}
formData.append('formData' myfile.files[i]);
function uploadcsvfile() {
    var myfile= document.getElementById("myfile");
    var formData = new FormData();
    if (myfile.value.toLowerCase().lastIndexOf(".csv") == -1) 
    {
      alert("Please upload a file with .csv extension.");
      return false;
    } 
    
    // else code to upload
}
<input type="file" id="myfile" class="required" multiple />
public async Task<JsonResult> UploadFile(List<IFormFile> formData)
{
      // do something here
}