将文件发布到不同服务器上的ashx页面

时间:2012-04-25 12:52:02

标签: asp.net file-upload ashx

我有一个asp.net网站,用户通过fileUpload Control选择一些文件。然后需要将文件发布到另一台服务器

我的域名是[http://www.mydomain.com]

我必须上传文件的地址如下:[https://www.externaldomain.com/upload.ashx?asd2t423eqwdq]

我尝试了以下内容:

Dim uploadedFiles As HttpFileCollection = Request.Files
Dim userPostedFile As HttpPostedFile = uploadedFiles(0)
Dim filePath As String

 filePath = "https://www.externaldomain.com/upload.ashx?asd2t423eqwdq" & "/" & userPostedFile.FileName


userPostedFile.SaveAs(filePath)

但我收到一个错误: SaveAs方法配置为需要根路径,路径“https://www.externaldomain.com/upload.ashx?asd2t423eqwdq/Core CSS 3.pdf”未植根

我搜索了互联网,但我找到的只是如何上传到该网页服务器的示例。

修改 我使用HttpWebRequest来访问该链接,并且它部分工作。我还需要发送2个POST参数,用户名和密码。

这就是我的代码现在的样子:

Dim link As String = "https://www.externaldomain.com/upload.ashx?e9879cc77c764220ae80"

Dim req As HttpWebRequest = WebRequest.Create(link)
Dim boundary As String = "-----"
req.ContentType = "multipart/form-data; boundary=" + boundary
req.Method = "POST"

Dim username As String = "test"
Dim userpass As String = "123456"


Dim credentials() As Byte = Encoding.UTF8.GetBytes("username=" & username & "&password=" & userpass & "--\r\n" & boundary & "--\r\n")



    Dim separators() As Byte = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n")

    Dim uploadedFiles As HttpFileCollection = Request.Files //this is where i take the file that the user wants to upload
    Dim userPostedFile As HttpPostedFile = uploadedFiles(0)


    //i convert the file to a byte array
    Dim binaryReader As IO.BinaryReader
    Dim fileBytes() As Byte
    binaryReader = New BinaryReader(userPostedFile.InputStream)
    fileBytes = binaryReader.ReadBytes(userPostedFile.ContentLength)

    //'get the request length
    req.ContentLength += credentials.Length
    req.ContentLength += userPostedFile.ContentLength
    req.ContentLength += separators.Length
    req.ContentLength += 1


    Dim dataStream As Stream
    dataStream = req.GetRequestStream

    dataStream.Write(credentials, 0, credentials.Length)
    dataStream.Write(separators, 0, separators.Length)
    dataStream.Write(fileBytes, 0, fileBytes.Length)

    dataStream.Close()

    Dim response As HttpWebResponse = req.GetResponse

我得到的错误是“禁止的”。用户名和密码是100%正确的。我认为问题是我没有正确创建请求。如果我只发布凭据我得到错误说我没有文件... 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

最后我使用了此处提供的代码http://aspnetupload.com/

我把它编译成了一个dll并添加了对我的解决方案的引用。 它有效:)