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

时间:2011-12-20 16:10:16

标签: 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的路径不是文件的正确路径。

我只是想从文件中获取数据,然后用它来处理。

这是这样做的吗?如果是这样,我怎么能让它工作?

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

感谢。

3 个答案:

答案 0 :(得分:3)

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

相反,您需要将上传表单POST到Web服务器并在此处理它。

答案 1 :(得分:0)

我不确定您为什么要将本地文件路径发送到webservice,然后尝试读取文件内容。这是不可能的。网络服务器无法查看或访问您的本地文件夹。您需要上传文件,然后您可以使用webservice调用获取成功上传文件的数据。

答案 2 :(得分:0)

<form action="MyPage/MyWebMethod.aspx" method="post" enctype="multipart/form-data" >
    <input type="file" id="fileTest"/>
    <input type="button" id="saveFile"/>
</form>

然后在服务器上,您可以从Request.Files访问文件。或类似的东西。我不记得请求的确切成员。 ajax也不是直接上传文件。有很多以ajax方式上传文件的技巧,其中一个是使用iframe。

相关问题