使用C#中的POST将文件上载到Web服务

时间:2012-08-06 19:13:33

标签: c# web-services api amazon-s3

此代码的问题在于文件上传后格式不正确。我正在尝试上传.zip文件。

public string HttpPost(string uri,string parameter)         {
            WebRequest webRequest = WebRequest.Create(uri);

        NetworkCredential credentials = new NetworkCredential("username", "password");
        webRequest.Credentials = credentials;

        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.Method = "POST";

        byte[] bytes = Encoding.ASCII.GetBytes(parameter);
        Stream os = null;
        try
        { // send the Post
            webRequest.ContentLength = bytes.Length;   //Count bytes to send
            os = webRequest.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);         //Send it
        }
        catch (WebException ex)
        {
            MessageBox.Show(ex.Message, "HttpPost: Request error",
               MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            if (os != null)
            {
                os.Close();
            }
        }

        try
        { // get the response
            WebResponse webResponse = webRequest.GetResponse();
            if (webResponse == null)
            { return null; }
            StreamReader sr = new StreamReader(webResponse.GetResponseStream());
            return sr.ReadToEnd().Trim();
        }
        catch (WebException ex)
        {
            MessageBox.Show(ex.Message, "HttpPost: Response error",
               MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        return null;
    } 

1 个答案:

答案 0 :(得分:1)

此示例如何在MyBucket中上传文件

    private const string KeyId = "Your KeyId";
    private const string AccessKey = "Your AccessKey";
    private const string S3Url = "https://s3.amazonaws.com/";

            private static void UploadFile()
    {
        var fileData = File.ReadAllBytes(@"C:\123.zip");

        string timeStamp = string.Format("{0:r}", DateTime.UtcNow);
        string stringToConvert = "PUT\n" +                               //Http verb
            "\n" +                                                       //content-md5
            "application/octet-stream\n" +                               //content-type
            "\n" +                                                       //date
            "x-amz-acl:public-read"+"\n" +                               //date
            "x-amz-date:" + timeStamp + "\n" +                           //optionall
            "/MyBucket/123.zip";                                         //resource
        var ae = new UTF8Encoding();
        var signature = new HMACSHA1 {Key = ae.GetBytes(AccessKey)};
        var bytes = ae.GetBytes(stringToConvert);
        var moreBytes = signature.ComputeHash(bytes);
        var encodedCanonical = Convert.ToBase64String(moreBytes);

        var url = "https://MyBucket.s3.amazonaws.com/123.zip";

        var request = WebRequest.Create(url) as HttpWebRequest;
        request.Method = "PUT";
        request.Headers["x-amz-date"] = timeStamp;
        request.Headers["x-amz-acl"] = "public-read";
        request.ContentType = "application/octet-stream";
        request.ContentLength = fileData.Length;
        request.Headers["Authorization"] = "AWS " + KeyId + ":" + encodedCanonical;

        var requestStream = request.GetRequestStream();
        requestStream.Write(fileData, 0, fileData.Length);
        requestStream.Close();

        using (var response = request.GetResponse() as HttpWebResponse)
        {
            var reader = new StreamReader(response.GetResponseStream());
            var data = reader.ReadToEnd();
        }
    }

查看Amazon S3 REST API