c# - 从上传的文件中读取文本 - C# 和 javascript

标签 c# javascript file-upload filereader

我有这样的东西:

<form action="" id="fileUpload">
    <input type="file" id="fileTest"/>
    <input type="button" id="saveFile"/>   </form>

供用户上传文件。

然后我有这个js:

$('#saveFile').click(function () {
    PageMethods.ReadFile($('#fileTest').val());
});

在我的 C# 代码中我这样做:

[WebMethod]
public static void ReadFile(string path)
{
    try
    {
        // Create an instance of StreamReader to read from a file.
        // The using statement also closes the StreamReader.
        using (StreamReader sr = new StreamReader(path))
        {
            String line;
            // Read and display lines from the file until the end of
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
    catch (Exception e)
    {
        // Let the user know what went wrong.
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(e.Message);
    }
}

但是发送到 webMethod 的路径不是文件的正确路径。

我只是想从文件中获取数据,然后用它做一些事情。

这是这样做的方法吗?如果是这样,我怎样才能让它发挥作用?

或者有更好的方法来做到这一点。

谢谢。

最佳答案

您正在尝试访问服务器上的客户端文件 ($('#fileTest'))。这是不可能的。

相反,您需要将上传表单发布到网络服务器并在该端进行处理。

关于c# - 从上传的文件中读取文本 - C# 和 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8578376/

相关文章:

c# - 如何在内存中创建Xml文件上传到服务器

c# - Automapper 忽略第一个源字段字母

c# - C#中的命名空间错误

java - 在java中读取文件上传的内容

javascript - onclick ="confirm()"取消按钮不工作

javascript - 使用 Python 中的请求从 __doPostBack 下载文本文件

php - Plupload 不上传文件

c# - 2 次调用或一次调用 sql server

c# - 在 Azure 中托管旧版 WCF 服务

javascript - 如何为日期添加天数?