public Task <UploadResponse> SaveToLocalStorage(Image <Rgba32> bitmapImage, string fileName) { if (!Directory.Exists(_uploadDir)) // checking if upload directory exists or not { Directory.CreateDirectory(_uploadDir); } var filePath = $"{$"IMG-{GetUnixEpochMethod(DateTime.Now)}-{fileName}".ToUrlSlug()}.jpeg"; var filePathUpdated = Path.Combine(_uploadDir, filePath); bitmapImage.Save(filePathUpdated, new JpegEncoder()); var bytes = ImageToByteArray(bitmapImage); var result = new UploadResponse() { Identifier = filePath, Width = bitmapImage.Width, Height = bitmapImage.Height, Url = $"{_localPath}/Uploads/{filePath}", Type = "image/jpeg", FileSize = SizeSuffix(bytes.Length) }; bitmapImage.Dispose(); return(Task.FromResult(result)); }
// - /umbraco/backoffice/EditorJs/ImageTool/UploadByUrl public JsonResult <UploadResponse> UploadByUrl() { UploadResponse r = new UploadResponse(0); var ctx = HttpContext.Current; var request = ctx.Request; string payload; using (Stream receiveStream = request.InputStream) { using (StreamReader readStream = new StreamReader(receiveStream, request.ContentEncoding)) { payload = readStream.ReadToEnd(); } } if (!string.IsNullOrWhiteSpace(payload)) { dynamic plobj = JsonConvert.DeserializeObject(payload); string imageurl = (string)plobj.url; if (!string.IsNullOrEmpty(imageurl)) { // - download the link's file content to the default upload-temp of Umbraco IPublishedContent media = MediaHelper.AddImageByUrl(Services.MediaService, Services.ContentTypeBaseServices, Umbraco, imageurl); r = MediaHelper.PrepareResponse(true, media); } } return(Json(r)); }
public async Task <UploadResponse> UploadAsync(Dictionary <string, object> transferMetadata = null, CancellationToken cancellationToken = default(CancellationToken)) { await PrepareAsync(cancellationToken).ConfigureAwait(false); CancellationTokenSource uploadCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); UploadResponse response = null; try { progressReporter.StartReporting(transferMetadata, uploadCancellationSource.Token); response = await InternalUploadAsync(uploadCancellationSource.Token).ConfigureAwait(false); } finally { uploadCancellationSource.Cancel(); uploadCancellationSource.Dispose(); } progressReporter.ReportCompletion(); try { FileStream.Dispose(); } catch (Exception) { // Eat the exception, we tried to clean up. } return(response); }
public void SendImageMessage(string user, XmlNode TSubResultNode) { string str_AccessToken = TokenBiz.GetAccessToken(str_corpid, str_corpsecret); SendImageRequest str = new SendImageRequest(); str.agentid = Agentid; str.safe = "0"; str.touser = user; SendImageRequest.Text image = new SendImageRequest.Text(); str.msgtype = TSubResultNode.SelectSingleNode("msgtype").InnerText; string picPath = HttpContext.Current.Request.PhysicalApplicationPath + TSubResultNode.SelectSingleNode("imagePath").InnerText; UploadResponse media_UpLoadInfo = MediaBiz.CreateInstance().Upload(picPath, str_AccessToken, EnumMediaType.image); if (media_UpLoadInfo != null) { image.media_id = media_UpLoadInfo.media_id; } str.image = image; messageBiz.Send <SendImageRequest>(str); if (!string.IsNullOrEmpty(TSubResultNode.SelectSingleNode("content").InnerText)) { SendSingleMessage(user, TSubResultNode); } }
public int Upload(string localPath, string remotePath, out UploadResponse uploadResponse) { if (UserInfo.UserName == "") { uploadResponse = null; return(-1); } string type = MimeMapping.GetMimeMapping(localPath); long size = new FileInfo(localPath).Length; string md5 = GetFileMD5(localPath); var client = new RestClient(ServerAddress.Address + "/api/storage/file"); var request = new RestRequest(Method.POST); request.AddHeader("Authorization", "Bearer " + UserInfo.Token); request.AddHeader("Content-Type", "application/json"); var requestBody = new { type, path = remotePath, size, md5 }; request.AddParameter("application/json", JsonConvert.SerializeObject(requestBody), ParameterType.RequestBody); IRestResponse response = client.Execute(request); Console.WriteLine(response.Content); uploadResponse = JsonConvert.DeserializeObject <UploadResponse>(response.Content); if (uploadResponse != null) { return(uploadResponse.status); } else { uploadResponse = null; return(-20000); } }
public int NewFolder(string folderPath, out UploadResponse uploadResponse) { if (UserInfo.UserName == "") { uploadResponse = null; return(-1); } var client = new RestClient(ServerAddress.Address + "/api/storage/file"); var request = new RestRequest(Method.POST); request.AddHeader("Authorization", "Bearer " + UserInfo.Token); request.AddHeader("Content-Type", "application/json"); var requestBody = new { type = "text/directory", path = folderPath, size = 0, md5 = "00000000000000000000000000000000" }; request.AddParameter("application/json", JsonConvert.SerializeObject(requestBody), ParameterType.RequestBody); IRestResponse response = client.Execute(request); Console.WriteLine(response.Content); uploadResponse = JsonConvert.DeserializeObject <UploadResponse>(response.Content); if (uploadResponse != null) { return(uploadResponse.status); } else { uploadResponse = null; return(-20000); } }
//private void OnSaveConfig(bool success, string data) //{ // Log.Debug("\tExampleRetrieveAndRank", "Retrieve and rank - Save config response: {0}", data); //Test(success); // _saveConfigTested = true; // Runnable.Run(ReadyToContinue(_waitTime)); //} private void OnUploadClusterConfig(UploadResponse resp, string data) { Log.Debug("\tExampleRetrieveAndRank", "Retrieve and rank - Upload cluster config response: {0}", data); Test(resp != null); _uploadClusterConfigTested = true; Runnable.Run(ReadyToContinue(_waitTime)); }
public ActionResult AsyncUploadDataFile(HttpPostedFileBase uploadFile) { string fileName = string.Empty; // The Name of the Upload component is "files" if (uploadFile != null) { // Some browsers send file names with full path. // We are only interested in the file name. fileName = Path.GetFileName(uploadFile.FileName); //var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName); fileName = GetPhysicalFileName(fileName); var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName); uploadFile.SaveAs(physicalPath); } // Return an empty string to signify success UploadResponse ur = new UploadResponse() { ErrorText = "", IsError = false, PhysicalFileName = fileName, ValidationReportFile = GetReportFileName(fileName) }; return(Content(JsonConvert.SerializeObject(ur))); }
private async Task <UploadResponse> ImportObject(UploadObject obj) { var uploadClient = new Client(new SwiftAuthManager(credentials)) .SetRetryCount(2) .SetLogger(new SwiftConsoleLog()); UploadResponse result = null; using (var stream = File.OpenRead(obj.Path)) { var response = await uploadClient.PutLargeObject(obj.Container, obj.Object, stream, null, null, Convert.ToInt64(ByteSize.FromMegabytes(10).Bytes)); if (response.IsSuccess) { result = new UploadResponse { IsSuccess = true }; } else { result = new UploadResponse { IsSuccess = false, Message = response.Reason }; } } return(result); }
public async Task UploadTestsAsync() { IAmazonS3 S3Client = TestingS3Client; ICloudStorage sut = new S3CloudStorage(S3Client); var uploadItems = PrepareUploadItems().ToList(); UploadResponse uploadResponse = await sut.UploadAsync(BucketName, uploadItems); Assert.Equal(ServiceStatusCode.OK, uploadResponse.StatusCode); Assert.Equal(2, uploadResponse.UploadedItems.Count); Assert.Collection(uploadResponse.UploadedItems, item => Assert.Contains("First/1.jpg", item.KeyName), item => Assert.Contains("Second/2.jpg", item.KeyName)); Assert.Equal(3, uploadResponse.FailedItems.Count); foreach (var fitem in uploadResponse.FailedItems) { switch (fitem.Source.KeyName) { case "": case null: Assert.Equal(UploadItemStatsCode.InvalidKeyName, fitem.StatusCode); break; case "Well/Good.key": Assert.Equal(UploadItemStatsCode.IOException, fitem.StatusCode); break; } } }
private static UploadedResponse PublishVideo(UploadResponse uploadResponse, string accessToken) { var request = WebRequest.Create("https://api.dailymotion.com/me/videos?url=" + HttpUtility.UrlEncode(uploadResponse.url) + "&fields=private_id,title"); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.Headers.Add("Authorization", "OAuth " + accessToken); var requestString = String.Format("title={0}&tags={1}&channel={2}&published={3}&private=true", HttpUtility.UrlEncode("some title"), HttpUtility.UrlEncode("tag1"), HttpUtility.UrlEncode("news"), HttpUtility.UrlEncode("true")); var requestBytes = Encoding.UTF8.GetBytes(requestString); var requestStream = request.GetRequestStream(); requestStream.Write(requestBytes, 0, requestBytes.Length); var response = request.GetResponse(); var responseStream = response.GetResponseStream(); string responseString; using (var reader = new StreamReader(responseStream)) { responseString = reader.ReadToEnd(); } var uploadedResponse = JsonConvert.DeserializeObject <UploadedResponse>(responseString); return(uploadedResponse); }
public async Task <IHttpActionResult> UploadAsync() { User user = await GetCurrentUserAsync() ?? throw new ActionForbiddenException(); Dictionary <string, byte[]> files = await ReadAsMultipartAsync(); KeyValuePair <string, byte[]> keyValuePair = files.FirstOrDefault(); IFileRepository repo = UnitOfWork.GetFileRepository(); File file = new File { CreateDt = DateTimeOffset.Now, Guid = Guid.NewGuid(), Name = keyValuePair.Key, User = user, Size = keyValuePair.Value.Length }; string path = PathHelper.GeneratePath(file.Guid); await _fileManager.WriteFileAsync(keyValuePair.Value, path); repo.Insert(file); await UnitOfWork.SaveChangesAsync(); UploadResponse response = new UploadResponse { Guid = file.Guid }; return(Ok(response)); }
public async Task <UploadResponse> FileUpload(byte[] imageBytes, string fileName) { var bucketName = this.bucket; UploadResponse obj = new UploadResponse(); try { var minio = new MinioClient(this.endpoint, accessKey, accessSecret); // Make a bucket on the server, if not already present. bool found = await minio.BucketExistsAsync(bucketName); if (!found) { await minio.MakeBucketAsync(bucketName, this.location); } using (var stream = new MemoryStream(imageBytes)) { // Upload a file to bucket. await minio.PutObjectAsync(bucketName, fileName, stream, stream.Length); } obj.Message = "Uploded Successfully."; obj.HasSucceed = true; obj.FileName = fileName; obj.FileUrl = this.BaseUrl + bucketName + "/" + fileName; } catch (MinioException e) { Console.WriteLine("File Upload Error: {0}", e.Message); obj.Message = "Uploaded failed with error " + e.message; obj.HasSucceed = false; obj.FileUrl = this.BaseUrl + bucketName + "/"; } return(obj); }
public async Task <bool> SendImage(string file, CancellationToken ct) { return(await Task.Factory.StartNew(() => { Login(); if (status != SolverStatus.Connected) { return false; } submissionId = null; UploadResponse result = client.Upload(file); if (ResponseStatus.success.Equals(result.status)) { submissionId = result.subid; Message = file; status = SolverStatus.ImageSent; return true; } Message = result.errormessage; return false; }, ct)); }
/// <summary> /// Request to upload file. Wraps UploadFile method with some output /// </summary> /// <param name="fileName">File name</param> /// <param name="fileUrl">File remote url</param> /// <param name="fileDigest">File SHA1 digest</param> /// <returns>Received token or empty string</returns> public static string RequestUploadFile(string fileName, string fileUrl, string fileDigest) { const string tag = "/api/file/upload.json"; WriteLine(tag, String.Format("Uploading file: {0}\n\tUrl: {1}", fileName, fileUrl)); // Upload request UploadResponse response = UploadFile(fileName, fileUrl, fileDigest); printResponse(response, tag); if (response != null && response.Status != "ok") { WriteLine(tag, "File could not be uploaded. Please ensure that file URL is accessible from the internet.\n"); } else if (response != null) { WriteLine(tag, "Received token:"); Console.WriteLine(response.Token + "\n"); return(response.Token); } return(String.Empty); }
public override async Task <UploadResponse> UploadFile(UploadRequest request, ServerCallContext context) { _logger.LogInformation($"File Received: {request.Name} | Size: {request.Content.Length} "); _db.Docs.Add(new Doc { Content = request.Content.ToArray(), ContentType = request.ContentType, PostId = request.PostId, FileName = request.Name, UserId = request.UserId }); await _db.SaveChangesAsync(); // Check if it was successful var response = new UploadResponse { Status = FileUploadStatus.Success, Message = $"File upload is done => {request.Name} | " + request.Content.Length }; return(response); }
public async Task <ActionResult> SaveImage(HttpPostedFileBase __filename, string __lastInternalName) { #endif FileUpload upload = new FileUpload(); string tempName = await upload.StoreTempImageFileAsync(__filename); if (!string.IsNullOrWhiteSpace(__lastInternalName)) // delete the previous file we had open { await upload.RemoveTempFileAsync(__lastInternalName); } Size size = await ImageSupport.GetImageSizeAsync(tempName); UploadResponse resp = new UploadResponse { Result = $"$YetaWF.confirm('{Utility.JserEncode(this.__ResStr("saveImageOK", "Image \"{0}\" successfully uploaded", __filename.FileName))}');", FileName = tempName, FileNamePlain = tempName, RealFileName = __filename.FileName, Attributes = this.__ResStr("imgAttr", "{0} x {1} (w x h)", size.Width, size.Height), }; return(new YJsonResult { Data = resp }); }
/// <summary> /// Upload a file to the server for future use such as e.g. an .SD file for publishing as a service. /// </summary> /// <param name="fi">The file to upload</param> /// <param name="description">An optional description of the file to be uploaded</param> /// <returns>UploadResponse object containing among other things an itemId identifying the uploaded file.</returns> public async Task <UploadResponse> UploadItem(System.IO.FileInfo fi, string description = "") { Uri uploadEndpoint = new Uri(ServerUrl, "uploads/upload"); MultipartFormDataContent content = new MultipartFormDataContent(); // setup file content and appropriate headers var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fi.FullName)); fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { FileName = fi.Name, Name = "itemFile" }; fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); content.Add(fileContent); // add description if provided if (!string.IsNullOrEmpty(description)) { content.Add(new StringContent(description), "description"); } UploadResponse response = await PostAsync <UploadResponse>(uploadEndpoint, content); return(response); }
/// <summary> /// Upload the file to the network. /// </summary> public static async Task <bool> UploadFile(int id, string fileLocation) { try { var res = await("http://localhost:3000/file/new") .PostMultipartAsync(mp => mp .AddStringParts(new { ownerID = id }) .AddFile("file", fileLocation) ).ReceiveString(); UploadResponse json = JsonConvert.DeserializeObject <UploadResponse>(res); if (json.success) { return(true); } else { return(false); } } catch { return(false); } }
public async Task <ActionResult> UploadSomething(HttpPostedFileBase __filename) #endif { // Save the uploaded file as a temp file FileUpload upload = new FileUpload(); string tempName = await upload.StoreTempImageFileAsync(__filename); // do something with the uploaded file "tempName" //... // Delete the temp file just uploaded await FileSystem.TempFileSystemProvider.DeleteFileAsync(tempName); bool success = true; string msg = this.__ResStr("uploadSuccess", "File {0} successfully uploaded", __filename.FileName); if (success) { UploadResponse resp = new UploadResponse { Result = $"$YetaWF.confirm('{Utility.JserEncode(msg)}', null, function() {{ /*add some javascript like $YetaWF.reloadPage(true); */ }} );", }; return(new YJsonResult { Data = resp }); } else { // Anything else is a failure throw new Error(msg); } }
public ActionResult Upload() { UploadResponse response = new UploadResponse(); if (Request.Files.Count == 0) { return(Json(response)); } var folder = Server.MapPath("~/upload"); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } foreach (string item in Request.Files) { var name = Guid.NewGuid().ToString("D"); var file = Request.Files[item]; var extension = Path.GetExtension(file.FileName); var path = Path.Combine(folder, name + extension); file.SaveAs(path); response.Items.Add("/upload/" + name + extension); } return(Json(response)); }
public ActionResult Index(HttpPostedFileBase uploadfile) { UploadResponse response = new UploadResponse(); if (uploadfile != null && uploadfile.ContentLength > 0) { ImageHandlerDBEntities db = new ImageHandlerDBEntities(); tbl_Image img = new tbl_Image(); img.CreateDate = DateTime.Now; img.ImageId = Guid.NewGuid(); img.ImageName = uploadfile.FileName; img.ImageType = uploadfile.ContentType; using (BinaryReader br = new BinaryReader(uploadfile.InputStream)) { img.ImageData = br.ReadBytes((int)uploadfile.InputStream.Length); } db.tbl_Image.Add(img); db.SaveChanges(); response.CreateDate = img.CreateDate; response.ImageId = img.ImageId; response.ImageType = img.ImageType; response.ImageName = img.ImageName; } return(View(response)); }
public async Task <ActionResult> ImportPackage(HttpPostedFileBase __filename) #endif { // Save the uploaded file as a temp file FileUpload upload = new FileUpload(); string tempName = await upload.StoreTempPackageFileAsync(__filename); // Import the package List <string> errorList = new List <string>(); bool success = await Package.ImportAsync(tempName, errorList); // Delete the temp file just uploaded await FileSystem.TempFileSystemProvider.DeleteFileAsync(tempName); string msg = FormatMessage(success, errorList, __filename.FileName); if (success) { UploadResponse resp = new UploadResponse { Result = $"$YetaWF.confirm('{Utility.JserEncode(msg)}', null, function() {{ $YetaWF.reloadPage(true); }} );", }; //System.Web.HttpRuntime.UnloadAppDomain(); //System.Web.HttpContext.Current.Response.Redirect("/"); return(new YJsonResult { Data = resp }); } else { // Anything else is a failure throw new Error(msg); } }
//private void OnSaveConfig(bool success, Dictionary<string, object> customData) //{ // Log.Debug("TestRetrieveAndRank.OnSaveConfig()", "{0}", customData["json"].ToString()); //Test(success); // _saveConfigTested = true; // Runnable.Run(ReadyToContinue(_waitTime)); //} private void OnUploadClusterConfig(UploadResponse resp, Dictionary <string, object> customData) { Log.Debug("TestRetrieveAndRank.OnUploadClusterConfig()", "{0}", customData["json"].ToString()); Test(resp != null); _uploadClusterConfigTested = true; Runnable.Run(ReadyToContinue(_waitTime)); }
public async Task <ActionResult> ImportModule(HttpPostedFileBase __filename, ImportModuleModel model) #endif { FileUpload upload = new FileUpload(); string tempName = await upload.StoreTempPackageFileAsync(__filename); List <string> errorList = new List <string>(); bool success = await ModuleDefinition.ImportAsync(tempName, model.CurrentPageGuid, true, model.ModulePane, model.ModuleLocation == Location.Top, errorList); await FileSystem.TempFileSystemProvider.DeleteFileAsync(tempName); string errs = ""; if (errorList.Count > 0) { ScriptBuilder sbErr = new ScriptBuilder(); sbErr.Append(errorList, LeadingNL: true); errs = sbErr.ToString(); } if (success) { string msg = this.__ResStr("imported", "\"{0}\" successfully imported(+nl)", __filename.FileName) + errs; UploadResponse resp = new UploadResponse { Result = $"$YetaWF.confirm('{Utility.JserEncode(msg)}', null, function() {{ $YetaWF.reloadPage(true); }} );", }; return(new YJsonResult { Data = resp }); } else { // Anything else is a failure throw new Error(this.__ResStr("cantImport", "Can't import {0}:(+nl)", __filename.FileName) + errs); } }
/// <summary> /// Upload file on cloud storage /// </summary> /// <param name="srcFile">Path to the file</param> /// <param name="dstPath">Name of the file on cloud</param> protected void UploadFile(string srcFile, string dstPath) { using (FileStream fs = new FileStream(srcFile, FileMode.Open)) { UploadResponse response = this.StorageApi.PutCreate(new PutCreateRequest(dstPath, fs)); Console.WriteLine($"File {dstPath} uploaded successfully with response {response.Status}"); } }
public UploadResponse Upload() { UploadResponse ww = new UploadResponse(); ww.wwretval = "Hello"; ww.wwrettext = "World"; return(ww); }
private UploadResult IsOkResponse(UploadResponse response) { var result = new UploadResult { Successful = response?.Status == "OK" }; return(result); }
public async Task <UploadResponse> SaveResponse(byte[] audioBytes, ProcessStatusEnum status) { var uploadResponse = new UploadResponse(); uploadResponse.GeneralStatusEnum = await Save(audioBytes, status); uploadResponse.Id = transcriptionId; return(uploadResponse); }
public async Task <UploadResponse> SaveResponse(byte[] imageBytes, ProcessStatusEnum status) { var uploadResponse = new UploadResponse(); uploadResponse.GeneralStatusEnum = await Save(imageBytes, status); uploadResponse.Id = id.ToString(); return(uploadResponse); }
public UploadResponse PostFile(string usuario, string item, string tipo, string tk) { using (PortalProContext ctx = new PortalProContext()) { if (!CntWebApiSeguridad.CheckTicket(tk, ctx) && tk != "solicitud") { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Se necesita tique de autorización (Carga de ficheros)")); } } UploadResponse uR = new UploadResponse(); uR.Usuario = usuario; uR.Item = item; uR.Tipo = tipo; string fileName = ""; HttpRequest request = HttpContext.Current.Request; foreach (string file in request.Files) { HttpPostedFile hpf = request.Files[file] as HttpPostedFile; if (hpf.ContentLength == 0) continue; // borrar posibles anteriores string fileDelete = String.Format("{0}-{1}-{2}-*", usuario, item, tipo); string root = AppDomain.CurrentDomain.BaseDirectory + "\\uploads"; foreach (FileInfo f in new DirectoryInfo(root).GetFiles(fileDelete)) { f.Delete(); } fileName = String.Format("{0}-{1}-{2}-{3}", usuario, item, tipo, Path.GetFileName(hpf.FileName)); string savedFileName = Path.Combine( root, fileName); hpf.SaveAs(savedFileName); } // obtener la raiz del servidor // comenzar a partir de 8 es para evitar '//' // Y ahora 9 porque hay https uR.Url = "url"; int pos = request.Url.AbsoluteUri.IndexOf("/", 9); if (pos > -1) uR.Url = request.Url.AbsoluteUri.Substring(0, pos) + "/uploads/" + fileName; uR.Status = 1; uR.Message = "message"; return uR; }
private async Task<UploadResponse> ImportObject(UploadObject obj) { var uploadClient = new Client(new SwiftAuthManager(credentials)) .SetRetryCount(2) .SetLogger(new SwiftConsoleLog()); UploadResponse result = null; using (var stream = File.OpenRead(obj.Path)) { var response = await uploadClient.PutLargeObject(obj.Container, obj.Object, stream, null, null, Convert.ToInt64(ByteSize.FromMegabytes(10).Bytes)); if (response.IsSuccess) { result = new UploadResponse { IsSuccess = true }; } else { result = new UploadResponse { IsSuccess = false, Message = response.Reason }; } } return result; }
//http://blog.building-blocks.com/uploading-images-using-the-core-service-in-sdl-tridion-2011 public static void UploadImages(string location, string folderTcmId, CoreService2010Client client, log4net.ILog Log) { //create a reference to the directory of where the images are DirectoryInfo directory = new DirectoryInfo(location); //create global Tridion Read Options ReadOptions readOptions = new ReadOptions(); //use Expanded so that Tridion exposes the TcmId of the newly created component readOptions.LoadFlags = LoadFlags.Expanded; try { //loop through the files foreach (FileInfo fileInfo in directory.GetFiles()) { //only allow images if (IsAllowedFileType(fileInfo.Extension)) { try { //create a new multimedia component in the folder specified ComponentData multimediaComponent = (ComponentData)client.GetDefaultData(Tridion.ItemType.Component, folderTcmId); multimediaComponent.Title = fileInfo.Name.ToLower(); multimediaComponent.ComponentType = ComponentType.Multimedia; multimediaComponent.Schema.IdRef = ConfigurationManager.AppSettings["MultimediaSchemaId"]; //create a string to hold the temporary location of the image to use later string tempLocation = ""; //use the StreamUpload2010Client to upload the image into Tridion UploadResponse us = new UploadResponse(); using (Tridion.StreamUpload2010Client streamClient = new StreamUpload2010Client()) { FileStream objfilestream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); tempLocation = streamClient.UploadBinaryContent(fileInfo.Name.ToLower(), objfilestream); } //creat a new binary component BinaryContentData binaryContent = new BinaryContentData(); //set this temporary upload location to the source of this binary binaryContent.UploadFromFile = tempLocation; binaryContent.Filename = fileInfo.Name.ToLower(); //get the multimedia type id binaryContent.MultimediaType = new LinkToMultimediaTypeData() { IdRef = GetMultimediaTypeId(fileInfo.Extension) }; multimediaComponent.BinaryContent = binaryContent; //save the image into a new object IdentifiableObjectData savedComponent = client.Save(multimediaComponent, readOptions); //check in using the Id of the new object client.CheckIn(savedComponent.Id, null); } catch (Exception ex) { Log.Debug("Error creating image " + fileInfo.Name, ex); } } } } catch (Exception ex) { Log.Error("Error processing images", ex); } finally { //clean up temp objects } }
private UploadResponse UploadFile(string b64hash, string type, long size, string path, string to, string contenttype) { ProtocolTreeNode media = new ProtocolTreeNode("media", new KeyValue[] { new KeyValue("xmlns", "w:m"), new KeyValue("hash", b64hash), new KeyValue("type", type), new KeyValue("size", size.ToString()) }); string id = TicketManager.GenerateId(); ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("to", WhatsConstants.WhatsAppServer), new KeyValue("type", "set") }, media); this.uploadResponse = null; this.WhatsSendHandler.SendNode(node); int i = 0; while (this.uploadResponse == null && i < 5) { i++; this.PollMessages(); } if (this.uploadResponse != null && this.uploadResponse.GetChild("duplicate") != null) { UploadResponse res = new UploadResponse(this.uploadResponse); this.uploadResponse = null; return res; } else { try { string uploadUrl = this.uploadResponse.GetChild("media").GetAttribute("url"); this.uploadResponse = null; Uri uri = new Uri(uploadUrl); string hashname = string.Empty; byte[] buff = MD5.Create().ComputeHash(System.Text.Encoding.Default.GetBytes(path)); StringBuilder sb = new StringBuilder(); foreach (byte b in buff) { sb.Append(b.ToString("X2")); } hashname = String.Format("{0}.{1}", sb.ToString(), path.Split('.').Last()); string boundary = "zzXXzzYYzzXXzzQQ"; sb = new StringBuilder(); sb.AppendFormat("--{0}\r\n", boundary); sb.Append("Content-Disposition: form-data; name=\"to\"\r\n\r\n"); sb.AppendFormat("{0}\r\n", to); sb.AppendFormat("--{0}\r\n", boundary); sb.Append("Content-Disposition: form-data; name=\"from\"\r\n\r\n"); sb.AppendFormat("{0}\r\n", this.phoneNumber); sb.AppendFormat("--{0}\r\n", boundary); sb.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", hashname); sb.AppendFormat("Content-Type: {0}\r\n\r\n", contenttype); string header = sb.ToString(); sb = new StringBuilder(); sb.AppendFormat("\r\n--{0}--\r\n", boundary); string footer = sb.ToString(); long clength = size + header.Length + footer.Length; sb = new StringBuilder(); sb.AppendFormat("POST {0}\r\n", uploadUrl); sb.AppendFormat("Content-Type: multipart/form-data; boundary={0}\r\n", boundary); sb.AppendFormat("Host: {0}\r\n", uri.Host); sb.AppendFormat("User-Agent: {0}\r\n", WhatsConstants.UserAgent); sb.AppendFormat("Content-Length: {0}\r\n\r\n", clength); string post = sb.ToString(); TcpClient tc = new TcpClient(uri.Host, 443); SslStream ssl = new SslStream(tc.GetStream()); try { ssl.AuthenticateAsClient(uri.Host); } catch (Exception e) { throw e; } List<byte> buf = new List<byte>(); buf.AddRange(Encoding.UTF8.GetBytes(post)); buf.AddRange(Encoding.UTF8.GetBytes(header)); buf.AddRange(File.ReadAllBytes(path)); buf.AddRange(Encoding.UTF8.GetBytes(footer)); ssl.Write(buf.ToArray(), 0, buf.ToArray().Length); //moment of truth... buff = new byte[1024]; ssl.Read(buff, 0, 1024); string result = Encoding.UTF8.GetString(buff); foreach (string line in result.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)) { if (line.StartsWith("{")) { string fooo = line.TrimEnd(new char[] { (char)0 }); JavaScriptSerializer jss = new JavaScriptSerializer(); UploadResponse resp = jss.Deserialize<UploadResponse>(fooo); if (!String.IsNullOrEmpty(resp.url)) { return resp; } } } } catch (Exception) { } } return null; }