我需要在silverlight项目中将文件上传到远程服务器。
以下是我的代码。我想上传一个PDF文件。
public bool UploadHelpDocument(string FileName, byte[] ms)
{
if (FileName != null)
{
if (ms.Length > 0)
{
FileUpload fu = new FileUpload();
string HelpDocPath = ConfigurationManager.AppSettings["HelpDocs"];
if (!Directory.Exists(HelpDocPath))
{
Directory.CreateDirectory(HelpDocPath);
}
if(fu.saveFileChunk(FileName, ms, HelpDocPath, 0) == true)
{
string fileURL = ConfigurationManager.AppSettings["HelpDocs"] + FileName;
byte[] localHelpfile = readLocalShapeFile(fileURL);
string sURL = "http://serverpath";
WebRequest request = WebRequest.Create(sURL);
request.ContentType = "application/ms-word";
request.Method = "PUT";
request.Credentials = new NetworkCredential("", "");
Stream requestStream = request.GetRequestStream();
requestStream.Write(localHelpfile, 0, localHelpfile.Length);
requestStream.Close();
WebResponse response = request.GetResponse();
return false;
}
}
}
return false;
}
我收到错误 WebResponse response = request.GetResponse(); 这条线。它说远程服务器返回错误:(405)Method Not Allowed。
出现此错误的原因可能是什么?
谢谢
答案 0 :(得分:0)
您想从Silverlight app发送WebRequest吗?
这样:
request.ContentType = "text/msword";
或
request.ContentType = "text/plain";
如果没有帮助,我认为服务器不处理PUT方法,需要研究目标服务器的配置。
1)如果您有权访问目标服务器,可以像这样在它们上创建crossdomain.xml或/和clientaccesspolicy.xml:
<强> clientaccesspolicy.xml 强>
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
<强>的crossdomain.xml 强>
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>
您可以阅读更多内容:
https://msdn.microsoft.com/en-us/library/cc197955%28VS.95%29.aspx
http://www.leggetter.co.uk/2008/10/24/how-to-make-a-cross-domain-web-request-with-silverlight-2.html
2)如果您无法访问目标服务器(更糟糕的消息)。您需要创建WebRequest绕过本地服务器。最好的方法是将Silverlight与WCF RIA服务集成。首先,您需要通过RIA服务将文件发送到本地服务器,然后从服务器发送,您需要将带有此文件的WebRequest发送到目标服务器无限制。
public void RIAHandleFile(byte[] file)
{
//(...)
requestStream.Write(file, 0, file.Length);
//(...)
}
在Silverlight中调用此函数,如
byte[] file;
InvokeOperation ria = domainContext.RIAHandleFile(file)