예제 #1
0
        /// <summary>
        ///     Upload files with additional data
        /// </summary>
        /// <param name="req">Http Url connection <see cref="HttpWebRequest" /></param>
        /// <param name="files">Http Files <see cref="UploadFile" /></param>
        /// <param name="form">Additional form data</param>
        /// <returns>
        ///     <see cref="HttpWebResponse" />
        /// </returns>
        public static HttpWebResponse Upload(HttpWebRequest req, UploadFile[] files, NameValueCollection form)
        {
            var mimeParts = new List<MimePart>();

            try {
                foreach (string key in form.AllKeys) {
                    var part = new StringMimePart();
                    part.Headers["Content-Disposition"] = "form-data; name=\"" + key + "\"";
                    part.StringData = form[key];
                    mimeParts.Add(part);
                }

                int nameIndex = 0;
                foreach (UploadFile file in files) {
                    var part = new StreamMimePart();
                    if (string.IsNullOrEmpty(file.FieldName))
                        file.FieldName = "file" + nameIndex++;

                    part.Headers["Content-Disposition"] = "form-data; name=\"" + file.FieldName + "\"; filename=\"" + file.FileName + "\"";
                    part.Headers["Content-Type"] = file.ContentType;
                    part.SetStream(file.Data);
                    mimeParts.Add(part);
                }

                string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
                req.ContentType = "multipart/form-data; boundary=" + boundary;
                //req.Method = "POST";
                byte[] footer = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
                long contentLength = mimeParts.Sum(part => part.GenerateHeaderFooterData(boundary));

                //foreach (MimePart part in mimeParts)
                //{
                //    contentLength += part.GenerateHeaderFooterData(boundary);
                //}
                req.ContentLength = contentLength + footer.Length;

                var buffer = new byte[8192];
                byte[] afterFile = Encoding.UTF8.GetBytes("\r\n");

                using (Stream s = req.GetRequestStream()) {
                    foreach (MimePart part in mimeParts) {
                        s.Write(part.Header, 0, part.Header.Length);
                        int read;
                        while ((read = part.Data.Read(buffer, 0, buffer.Length)) > 0)
                            s.Write(buffer, 0, read);
                        part.Data.Dispose();
                        s.Write(afterFile, 0, afterFile.Length);
                    }
                    s.Write(footer, 0, footer.Length);
                }
                return (HttpWebResponse) req.GetResponse();
            }
            catch {
                foreach (MimePart part in mimeParts) {
                    if (part.Data != null)
                        part.Data.Dispose();
                }
                throw;
            }
        }
예제 #2
0
        /// <summary>
        ///     Upload files with additional data
        /// </summary>
        /// <param name="url">Url</param>
        /// <param name="files">files</param>
        /// <param name="form">additional data</param>
        /// <returns></returns>
        public static string Upload(string url, UploadFile[] files, NameValueCollection form)
        {
            HttpWebResponse resp = Upload((HttpWebRequest) WebRequest.Create(url), files, form);

            using (Stream s = resp.GetResponseStream()) {
                if (s == null) return null;
                using (var sr = new StreamReader(s)) return sr.ReadToEnd();
            }
        }
예제 #3
0
        /// <summary>
        ///     This method uploads files onto the remote server using the POST method
        /// </summary>
        /// <param name="path">Resource Path</param>
        /// <param name="uploadFiles">Files to upload</param>
        /// <param name="parameters">Additional form data</param>
        /// <returns>HttpResponse Object</returns>
        /// <exception cref="HttpRequestException"></exception>
        /// <exception cref="Exception"></exception>
        public HttpResponse PostFiles(string path, UploadFile[] uploadFiles, ParameterMap parameters)
        {
            HttpResponse response = null;
            try {
                Connected = false;
                // Let us open the connection, prepare it for writing and reading data.
                HttpWebRequest urlConnection = OpenConnection(path);
                urlConnection.Accept = Accept;
                urlConnection.KeepAlive = true;
                urlConnection.ReadWriteTimeout = ReadWriteTimeout*1000;
                urlConnection.Timeout = ConnectionTimeout*1000;
                urlConnection.Method = "POST";
                urlConnection.Headers.Add("Accept-Charset", "UTF-8");
                AppendRequestHeaders(urlConnection);
                Connected = true;

                // Build form data to send to the server.
                // Let us set the form data
                NameValueCollection form = parameters.ToNameValueCollection();

                // upload the files
                HttpWebResponse resp = HttpUploadHelper.Upload(urlConnection, uploadFiles, form);
                using (resp) {
                    if (resp != null) {
                        using (Stream inputStream = resp.GetResponseStream()) {
                            if (inputStream != null) {
                                var buffer = new byte[resp.ContentLength];
                                int bytesRead = 0;
                                int totalBytesRead = bytesRead;
                                while (totalBytesRead < buffer.Length) {
                                    bytesRead = inputStream.Read(buffer, bytesRead, buffer.Length - bytesRead);
                                    totalBytesRead += bytesRead;
                                }
                                response = new HttpResponse(urlConnection.Address.AbsoluteUri, urlConnection.Headers, Convert.ToInt32(resp.StatusCode), buffer);
                            }
                        }
                    }
                }
                return response;
            }
            catch (Exception e) {
                if (e.GetType() == typeof (WebException)) {
                    var ex = e as WebException;
                    try { response = ReadStreamError(ex); }
                    catch (Exception ee) {
                        // Must catch IOException, but swallow to show first cause only
                        RequestLogger.Log(ee.StackTrace);
                    }
                    finally {
                        if (response == null
                            || response.Status <= 0)
                            throw new HttpRequestException(e, response);
                    }
                }
                else {
                    // Different Exception 
                    // Must catch IOException, but swallow to show first cause only
                    RequestLogger.Log(e.ToString());
                }
            }
            finally {
                // Here we log the Http Response
                if (RequestLogger.IsLoggingEnabled()) RequestLogger.LogResponse(response);
            }
            return response;
        }
예제 #4
0
        /// <summary>
        ///     Upload a new content media file with content media metadata
        /// </summary>
        /// <param name="filePath">Content Media file</param>
        /// <param name="mediaInfo">Content Media Info</param>
        /// <returns>
        ///     <see cref="ContentMedia" />
        /// </returns>
        /// <exception cref="Exception">Exception with the appropriate message.</exception>
        public ContentMedia AddContentMedia(string filePath, MediaInfo mediaInfo)
        {
            const string resource = "/media/";
            if (mediaInfo == null) throw new Exception("Parameter 'mediaInfo' cannot be null.");
            ParameterMap parameterMap = RestClient.NewParams();
            parameterMap.Set("ContentName", mediaInfo.ContentName)
                .Set("LibraryId", mediaInfo.LibraryId.ToString())
                .Set("DestinationFolder", mediaInfo.DestinationFolder ?? string.Empty)
                .Set("Preference", mediaInfo.Preference)
                .Set("Width", Convert.ToString(mediaInfo.Width))
                .Set("Height", Convert.ToString(mediaInfo.Height))
                .Set("DrmProtect", mediaInfo.DrmProtect ? "true" : "false")
                .Set("Streamable", mediaInfo.Streamable ? "true" : "false")
                .Set("DisplayText", mediaInfo.DisplayText ?? string.Empty)
                .Set("ContentText", mediaInfo.ContentText ?? string.Empty)
                .Set("Tags", mediaInfo.Tags != null && mediaInfo.Tags.Count > 0 ? JsonConvert.SerializeObject(mediaInfo.Tags) : string.Empty);

            // Let us build the upload file
            var mediaFile = new UploadFile(filePath, "MediaFile", FileExtensionMimeTypeMapping.GetMimeType(Path.GetExtension(filePath)));
            UploadFile[] files = {mediaFile};
            HttpResponse response = RestClient.PostFiles(resource, files, parameterMap);
            if (response == null) throw new Exception("Request Failed. Unable to get server response");
            if (response.Status == Convert.ToInt32(HttpStatusCode.Created)) return new ContentMedia(JsonConvert.DeserializeObject<ApiDictionary>(response.GetBodyAsString()));
            string errorMessage = String.Format("Status Code={0}, Message={1}", response.Status, response.GetBodyAsString());
            throw new Exception("Request Failed : " + errorMessage);
        }