【问题标题】:Post file to ashx page on different server将文件发布到不同服务器上的 ashx 页面
【发布时间】:2012-04-25 12:52:02
【问题描述】:

我有一个 asp.net 网站,用户可以在其中选择一些带有文件上传控件的文件。然后需要将文件发布到另一台服务器

我的域名是 [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%正确。我认为问题在于我没有正确创建请求。如果我只发布凭据,我会收到错误消息,说我没有文件... 有什么想法吗?

【问题讨论】:

  • 您需要使用 System.Net.WebRequest 类并向其他网站发出 post 请求。您可以在此处找到示例代码。 msdn.microsoft.com/en-us/library/debx8sh9.aspx
  • http://forums.asp.net/t/1612178.aspx 的程序员有同样的任务要做。希望这可以帮助你。
  • 我使用了来自 msdn 的链接,但我仍然遇到了一些麻烦。我编辑了我的初始帖子并添加了新代码。我不知道如何使用 post 参数发送用户名、密码和内容。

标签: asp.net file-upload ashx


【解决方案1】:

最终我使用了这里提供的代码http://aspnetupload.com/

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

【讨论】:

    猜你喜欢
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    相关资源
    最近更新 更多