是否可以通过Jquery .ajax()方法在webmethod中使用path获取文件

Is it possible to get a file in webmethod using path through Jquery .ajax() method?

本文关键字:path 文件 获取 webmethod Jquery 可以通过 ajax 方法 是否      更新时间:2023-09-26

据我所知,使用Jquery/Ajax调用发送文件到webmethod是不可能的。但是如果我发送文件的路径呢?然后用那个路径在webmethod中获取文件?

客户端:

 $.ajax({
            type: "POST",
            url: "Default.aspx/UploadFile",
            data: JSON.stringify({ name: $('#fileData').val(); }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            success: function (data, status) {
                console.log("CallWM");
                alert(data.d);
            },
            failure: function (data) {
                alert(data.d);
            },
            error: function (data) {
                alert(data.d);
            }
        });

WebMethod:

 [WebMethod]
    public static string UploadFile(string name)
    {
        byte[] buffer;
        FileStream fileStream = new FileStream(@"D:'Untitled.png", FileMode.Open, FileAccess.Read);
        try
        {
            int length = (int)fileStream.Length;  // get file length
            buffer = new byte[length];            // create buffer
            int count;                            // actual number of bytes read
            int sum = 0;                          // total number of bytes read
            // read until Read method returns 0 (end of the stream has been reached)
            while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                sum += count;  // sum is a buffer offset for next reading
        }
        finally
        {
            fileStream.Close();
        }
        return "a";
    }

这个可行吗?我认为大多数现代浏览器不允许您获得文件的真实路径。有什么解决办法吗?

不,这不能工作。嗯,你说的是两码事。您发送的文件路径将在服务器上解析。如果要上传文件,则需要从客户端发送。你搞混了很多东西。

想象一下,你试着把这个发送到服务器:C:'Users'yourName'Test.txt,您认为服务器将在哪里查找文件?服务器将在他的本地驱动器上搜索。

尝试使用默认方式上传文件。也许用一些jQuery插件,你在后台发出请求。互联网将为您的场景提供大量教程。谷歌一下就知道了

不行,这行不通。如果你想上传文件而不返回整个页面,你可以使用iframe并将提交表单的目标设置为这个iframe

虽然不确定,但您可以尝试HttpPostedFileBase

foreach (string one in Request.Files)
{
     HttpPostedFileBase file = Request.Files[one];
     if ((file != null) && (file.ContentLength > 0) &&    !string.IsNullOrEmpty(file.FileName))
     {
         string fileName = file.FileName;
         string fileContentType = file.ContentType;
         byte[] fileBytes = new byte[file.ContentLength];
         BinaryReader b = new BinaryReader(file.InputStream);
         byte[] binData = b.ReadBytes(file.ContentLength);
     }
}

我相信你可以发送一个文件到webmethod只是为了简化使用Base64的事情

读取你的文件为字节,将你的字节转换为Base64,例如

var bytes = File.ReadAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "filename.extension"));

则可以转换为Base64

var stringBase64=Convert.ToBase64String(bytes);

然后在另一端将接收到的base64字符串转换为字节

var bytes = Convert.FromBase64String(ReceivedString);

就这些