我有这样的东西:
<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/