如何通过REST服务发送本地文件
本文关键字:文件 何通过 REST 服务 | 更新日期: 2024-09-23 15:44:13
我正在使用WCF和C#开发REST web服务(VS 2010)。我想开发一个这样的操作:
doSomethingWithAFile(String filePath)
所以它会被这样调用:
GET http://my.web.service/endpoint?filePath={filePath}
filePath
是客户端(而不是服务器)中的文件路径。因此,当被调用时,该操作必须将路径指向的文件发送到服务器,以便服务器可以对文件中包含的数据执行一些操作。
我怎样才能做到这一点?
编辑:正如我在评论中所说,我会在客户端中设置一个共享文件夹,所以我发送路径,服务器读取文件夹中的文件。
在您的服务器上,您必须有一个带有接受字符串输入的方法的服务,您可以使用客户端应用程序的文件路径来调用该方法
然后,您可以通过正常的文件IO方法在服务器上从该位置读取/复制/任意文件。
你可以在下面找到一个如何做到这一点的例子。ServerPleaseFetchThisFile
的定义自然取决于它将是什么类型的web服务,WCF或IIS web服务或自制web服务。
public bool ServerPleaseFetchThisFile(string targetPath)
{
// targetPath should enter from the client in format of ''Hostname'Path'to'the'file.txt
return DoSomethingWithAFile(targetPath);
}
private bool DoSomethingWithAFile(string targetFile)
{
bool success = false;
if (string.IsNullOrWhiteSpace(targetFile))
{
throw new ArgumentNullException("targetFile", "The supplied target file is not a valid input.");
}
if (!File.Exists(targetFile))
{
throw new ArgumentNullException("targetFile", "The supplied target file is not a valid file location.");
}
try
{
using (FileStream targetStream = new FileStream(targetFile, FileMode.Open, FileAccess.Read))
{
// Do something with targetStream
success = true;
}
}
catch (SecurityException se)
{
throw new Exception("Security Exception!", se);
// Do something due to indicate Security Exception to the file
// success = false;
}
catch (UnauthorizedAccessException uae)
{
throw new Exception("Unathorized Access!", uae);
// Do something due to indicate Unauthorized Access to the file
// success = false;
}
return success;
}