programing

Asp에서 Ajax를 사용하여 파일을 업로드하고 있습니다.넷코어

lovecodes 2023. 3. 26. 12:12
반응형

Asp에서 Ajax를 사용하여 파일을 업로드하고 있습니다.넷코어

여러분 안녕하세요.

클라이언트측에서 서버측(asp.net 코어) 컨트롤러에 Ajax를 사용하여 파일을 업로드하려고 하는데 null 값이 있습니다.

다음은 저의 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>

IForm File을 사용하는 컨트롤러입니다.

public async Task<JsonResult> UploadFile(IFormFile formData)
{
      // do something here
}

잘 부탁드립니다!

여기에 잘 설명되어 있습니다.

브라우저 측 코드:

HTML

<form id="form" name="form" action="/uploader" enctype="multipart/form-data" method="post">
  <div class="buttons">
    <div class="upload-button">
      <div class="label">Click me!</div>
      <input id="files" name="files" type="file" size="1" multiple onchange="uploadFiles('files');" />
    </div>
  </div>
</form>

자바스크립트

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: "/uploader",
      data: formData,
      processData: false,
      contentType: false,
      type: "POST",
      success: function (data) {
        alert("Files Uploaded!");
      }
    }
  );
}

서버측 코드:

[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;
}

다음은 컨트롤러의 작업에 파일을 게시하는 간단한 방법입니다.

표시:

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);   
}

(.)를 사용한 완전 동작 예넷 코어)상기 답변 중 일부는 컴파일 오류를 수정하여 답변합니다.

파일을 업로드 할 경우 업로드된 파일과 함께 양식을 제출합니다.

Register.cshtml

@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}";
    }
 }
}

Register Model 클래스

namespace UploadFileAjaxPostWebApp.Models.Account
{
  public class RegisterModel
  {
    public string FirstName { get; set; }

    public string SecondName { get; set; }

    public string ResumeFileName { get; set; }
  }
}

파일 입력 "name" 속성을 지정하기만 하면 됩니다(ASP의 변수 이름과 동일).NET 컨트롤러).HTML:

<input type="file" name="thefile" />

C#:

public ActionResult UploadFile(IFormFile thefile) { }

AJAX 요청의 경우 FormData 개체에 적절한 이름을 지정해야 합니다.

매개 변수 이름이 달라 null 값을 가져오는 중입니다.

클라이언트 측:file-i를 설정하는 대신 fromData를 액션 메서드 파라미터 이름과 동일하게 추가합니다.

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

csv 파일을 업로드 할 때 검증을 추가하여 csv 파일만 허용합니다.

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
}

여러 파일을 업로드 할 때

Html: 여러 특성 추가

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

Server Side:IFrom 파일 목록 추가

public async Task<JsonResult> UploadFile(List<IFormFile> formData)
{
      // do something here
}

폼 태그를 사용하지 않을 경우 @Html을 추가합니다.위조 방지토큰()

var GetImages = $('[name="Images"]');
console.log(GetImages[0].files)

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

언급URL : https://stackoverflow.com/questions/46903310/uploading-file-using-ajax-in-asp-net-core

반응형