コード例 #1
0
        /// <summary>
        /// Synchronously uploads the file to Uploadcare.
        /// 
        /// The calling thread will be busy until the upload is finished.
        /// </summary>
        /// <returns> An Uploadcare file </returns>
        /// <exception cref="UploadFailureException"> </exception>
        public UploadcareFile Upload(bool? store = null)
        {
            var url = Urls.UploadBase();

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";

            try
            {
                var boundary = "Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture);
                using (var content = new MultipartFormDataContent(boundary))
                {
                    content.Add(new StringContent(_client.PublicKey), "UPLOADCARE_PUB_KEY");
                    if (store != null)
                        if (store.Value)
                            content.Add(new StringContent("1"), "UPLOADCARE_STORE");
                    else
                        content.Add(new StringContent("0"), "UPLOADCARE_STORE");
                    else
                        content.Add(new StringContent("auto"), "UPLOADCARE_STORE");
                    if (_file != null)
                        content.Add(new StreamContent(File.OpenRead(_file.FullName)), "file", _file.Name);
                    else
                        content.Add(new ByteArrayContent(_bytes), "file", _fileName);

                    var buffer = content.ReadAsByteArrayAsync().Result;
                    using (var reqStream = request.GetRequestStream())
                    {
                        reqStream.Write(buffer, 0, buffer.Length);
                    }

                    request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

                    var fileId = _client.GetRequestHelper().ExecuteQuery(request, false, new UploadBaseData()).File;

                    return _client.GetFile(fileId);
                }
            }
            catch (Exception)
            {
                throw new UploadFailureException();
            }
        }