ASP.NET从Javascript发送文件文件上传到WebMethod C#

deyfvvtc  于 2022-11-19  发布在  .NET
关注(0)|答案(1)|浏览(141)

虽然还有其他类似的帖子,但没有一篇真正关注使用Javascript PageMethod文件上传的ASP.NET网站。我想从我的文件选择器中选择一个文件(它正在工作),并将其发送到WebMethod进行上传。
我已经设法选择了该文件并将其发送到我的WebMethod。但是,我不确定如何将该对象转换为C#中可读的格式。它是CSV文件。

Javascript:

<script>
            //formstone file drop picker library
            $(".upload").upload({
                beforeSend: onBeforeSend
            });

            function onBeforeSend(formData, file) {
                if (file.name.indexOf(".csv") < 0) {
                    return false;
                }

                //file is successfully received here
                var fd = new FormData();
                fd.append(file.name, file);
    
                //this gets called as well
                PageMethods.set_path("manage-products.aspx");
                PageMethods.UploadCSV(file, onSuccess, onFailure);

                function onSuccess(response) {
                }

                function onFailure() {
                    console.log("FAIL");
                }

                return formData;
            }
      </script>

C#Web方法:

[WebMethod]
public static void UploadCSV(object formData)
{ 
    //I'm trying to get the file data and convert to a readable file here
}
kqlmhetl

kqlmhetl1#

我觉得这个问题已经回答了。有几种方法可以接受一个文件在一个C# controller
其中一条是这样的:

[APIController]
[HttpPost]
public ActionResult Post(IFormFile myFile)
{
if(myFile==null)
{//ErrorHandling
 return BadRequest();
}
//do what ever you please with your file here
return Ok();
}

上面的例子对我来说是最容易理解和实现的方法。也许它对你有用。只要在这个控制器上打开Swagger,在你的浏览器中按F12并使用端点。你会在浏览器开发工具的网络部分看到如何实现对控制器的请求。

相关问题