如何使用webservice将文件从客户端machin上传到服务器

问题描述:

How to upload a file from client machin to server by using webservice

I have created webservice using C#.That take filepath/url(object from client pc ,not hosted anywhere),convert to byte array.And using that create a file on server location.Below code working fine on local machine.I uploaded file from C drive to D drive.But when I hosted service on server not localhost and trying to access,file not get uploaded and getting msg like this : Could not find file 'C:\Fileupload\test.txt'..Client can send only url of file that from local machine not hosted anywhere can not send byte array.Is there any option apart from creating new file in server.Can I directly upload like fileuploadcontrol.Client can either use web app or windows app or windows service for uploading





我尝试过:





What I have tried:

Here is my code :

string uploadFolder = = @"D:\UploadFiles\"; 

[WebMethod]
public string UploadFile(string filePath)
{

try
{

byte[] f = System.IO.File.ReadAllBytes(filePath);
MemoryStream ms = new MemoryStream(f);

uploadFolder = uploadFolder + StrFilename;
// StrFilename extracted from filepath

FileStream fs = new FileStream(uploadFolder, FileMode.Create);

ms.WriteTo(fs);
ms.Close();
fs.Close();
fs.Dispose();

return "OK";
}

}
catch (Exception ex)
{
// return the error message if the operation fails
return ex.Message.ToString();
}

}

它在本地计算机上工作,因为客户端和服务器都是同一台机器,所以当客户端发送c:\ file.txt时,可以在服务器代码中读取该文件。部署站点时,客户端和服务器是不同的计算机,因此当您发送c:\ file.txt时,该服务器上不存在该文件,因此无法读取该文件。请记住,您的.net代码没有在浏览器中的客户端计算机上运行,​​因此它无法访问客户端文件系统,如果可能的话,这将是一个巨大的安全问题。



谷歌如何将文件上传到网络服务,具体取决于你正在做什么,但最终你需要一个文件类型的输入控件,并将其发布到你的网络服务或序列化它通过html5文件api并将其发布到Web服务。就像我说的那样,谷歌提供了确切的代码,但你现在所做的事情根本不起作用。
It worked on your local machine as the client and server are the same machine so when the client sends "c:\file.txt" that file can be read in your server code. When you deploy your site the client and server are different machines so when you send "c:\file.txt" that file does not exist on the server so it can't read it. Remember that your .net code isn't running on the client machine in the browser so it can't access the client file system, it would be a huge security concern if it could.

Google how to upload a file to a web service, the specifics depend on what you're doing but ultimately you'll need an input control of type "file" and either post that to your web service or serialise it via the html5 file api and post it to the web service that way. As I said, google for exact code, but what you're doing now simply isn't going to work.