【问题标题】:Uploading a file to a web service using POST in C#在 C# 中使用 POST 将文件上传到 Web 服务
【发布时间】:2012-08-06 19:13:32
【问题描述】:

此代码的问题在于文件在上传后不是正确的格式。我正在尝试上传 .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;
    } 

【问题讨论】:

  • 您使用的是哪个网络服务平台? ASMX、WCF(RESTful 还是 SOAP?)、ASP.NET MVC Web-API 等?
  • 您正在尝试上传 zip 文件,因此内容类型应为 application/octet-stream
  • 如何编码。它还会是我所拥有的吗? byte[] bytes = Encoding.ASCII.GetBytes(参数);
  • 您有许多实现IDisposable 的实例,因此它们应该位于using 块中。
  • 由于某种原因上传文件时,文件名是:98A12C12-870C-42DA-9EF8-5278B7C9BD9F,当我点击打开时,它不是图片。我不确定我在这里缺少什么。

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


【解决方案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

【讨论】:

    猜你喜欢
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多