使用HTTPS POST请求上传PDF文件(C#)

时间:2014-03-19 01:30:22

标签: c# pdf post file-upload multipartform-data

我一直在尝试使用表单编码的HTTPS请求上传PDF文件。在我的下面的方法中,我可以成功上传文本文件但是当我尝试使用PDF时,我得到一个禁止的错误(403)。我一直在网上搜索答案,但没有发现如何解决这个问题......

我尝试使用WriteAllBytes和CopyTo方法转换PDF然后将其写入流中,但两次都出现了同样的错误。

public void CreateFile(string parentID, string filePath)
{
    Stream stream;
    string extension = Path.GetExtension(filePath).ToLower().Replace(".", "");
    string fileName = Path.GetFileName(filePath);

    var request = (HttpWebRequest)WebRequest.Create("https://someurl/upload/");

    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
    request.ContentType = "multipart/form-data; boundary=" + boundary;
    request.Method = "POST";
    request.KeepAlive = true;
    request.Credentials = ConnectedUser.AssignedOwner.NetworkCredentials;

    var data = "--" + boundary + "\n"; 
    data += "Content-Disposition: form-data; name=\"parent\"\n\n" + parentID + "\n"; 
    data += "--" + boundary + "\n"; 
    data += "Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\n";
    data += "Content-Transfer-Encoding: binary\n\n";

    switch (extension)
    {
        // This works
        case "txt":
            data += "Content-Type: text/plain\n";
            data += "Content-Transfer-Encoding: binary\n\n";

            data += File.ReadAllText(filePath) + "\n";
            data += "--" + boundary + "--\n";

            var bData = Encoding.ASCII.GetBytes(data);
            request.ContentLength = bData.Length;

            stream = request.GetRequestStream();           
            stream.Write(bData, 0, bData.Length);
            break;

        // This doesn't work
        case "pdf":
            using (var s = File.Open(filePath, FileMode.Open))
            {
                data += "Content-Type: application/pdf\n";
                data += "Content-Transfer-Encoding: binary\n\n";

                byte[] bDataPDF = Encoding.ASCII.GetBytes(data);
                string footer = "--" + boundary + "--\n";
                byte[] bFooter = Encoding.ASCII.GetBytes(footer);
                request.ContentLength = bDataPDF.Length + s.Length + bFooter.Length;

                stream = request.GetRequestStream();
                stream.Write(bDataPDF, 0, bDataPDF.Length);
                s.CopyTo(stream);
                stream.Write(bFooter, 0, bFooter.Length);  
            }
            break;
        default:
            break;
    }

    var response = (HttpWebResponse)request.GetResponse();
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}

0 个答案:

没有答案