Beispiel #1
0
        public async Task <AkeneoResponse> UploadAsync(MediaUpload media, CancellationToken ct = default(CancellationToken))
        {
            if (!File.Exists(media.FilePath))
            {
                throw new FileNotFoundException($"File with path {media.FilePath} not found.");
            }
            var filename    = media.FileName ?? Path.GetFileName(media.FilePath);
            var formContent = new MultipartFormDataContent
            {
                { new JsonContent(media.Product, AkeneoSerializerSettings.Update), "product" },
                { new StreamContent(File.OpenRead(media.FilePath)), "file", filename }
            };

            _logger.Debug($"Preparing to upload image '{filename}' from '{media.FilePath}'.");
            var response = await HttpClient.PostAsync(Endpoints.MediaFiles, formContent, ct);

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                await AddAuthHeaderAsync(ct);

                response = await HttpClient.PostAsync(Endpoints.MediaFiles, new MultipartFormDataContent
                {
                    { new JsonContent(media.Product, AkeneoSerializerSettings.Update), "product" },
                    { new StreamContent(File.OpenRead(media.FilePath)), "file", filename }
                }, ct);
            }
            return(response.IsSuccessStatusCode
                                ? AkeneoResponse.Success(response.StatusCode, new KeyValuePair <string, PaginationLink>(PaginationLinks.Location, new PaginationLink {
                Href = response.Headers?.Location?.ToString()
            }))
                                : await response.Content.ReadAsJsonAsync <AkeneoResponse>());
        }
        public ActionResult Guncelle(UserUpdateModel model)
        {
            if (model.Kullanici != null)
            {
                if (model.ProfilPic != null)
                {
                    #region UploadPhotoSaveToDatabase
                    MediaUpload m = new MediaUpload();
                    m = UploadSaveToDatabase(model.ProfilPic);
                    _uow.GetRepo <MediaUpload>()
                    .Add(m);
                    _uow.Commit();
                    #endregion
                    model.Kullanici.ProfilPic = m.Path.ToString();
                }

                _uow.GetRepo <Kullanici>()
                .Update(model.Kullanici);

                if (_uow.Commit() > 0)
                {
                    return(RedirectToAction("Listele", "User"));
                }
            }
            return(View());
        }
        public ActionResult Upload(MediaUpload mediaUpload, HttpPostedFileBase file)
        {
            try
            {
                if (file.ContentLength > 0)
                {
                    var uploadedMedia = new UploadedMedia();
                    uploadedMedia.FileName    = file.FileName;
                    uploadedMedia.Length      = file.ContentLength;
                    uploadedMedia.ContentType = file.ContentType;

                    using (var reader = new System.IO.BinaryReader(file.InputStream))
                    {
                        uploadedMedia.Stream = reader.ReadBytes(file.ContentLength);
                    }
                    this._mediaUploadService.Process(uploadedMedia, mediaUpload.DataClassification);
                    ViewBag.Message = "File Uploaded Successfully!!";
                }
                else
                {
                    ViewBag.Message = "No file uploaded.";
                }

                return(View());
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return(View());
            }
        }
Beispiel #4
0
        public ActionResult Upload(IEnumerable <HttpPostedFileBase> files)
        {
            foreach (HttpPostedFileBase item in files)
            {
                string uniqueFileName = Guid.NewGuid().ToString();
                string extention      = Path.GetExtension(item.FileName);
                //fiziksel dosya konumunu belirttik
                //HttpContext.Server.MapPath() bulunduğumuz web dizini gönderir.
                string fullFileName = HttpContext.Server.MapPath("/Media/Images/" + uniqueFileName + extention);

                //bu itemi şu dizine kaydet demek
                item.SaveAs(fullFileName);
                MediaUpload upload = new MediaUpload();
                upload.Name = uniqueFileName + extention;
                upload.Path = "/Media/Images/" + uniqueFileName + extention;
                _uow.GetRepo <MediaUpload>()
                .Add(upload);
                _uow.Commit();
                //yeni bir dosya açmak için
                //System.IO.File.Create(fullFileName);

                //dosya silme işlemi klasörden silme
                //System.IO.File.Delete(fullFileName);

                // Dosya Var Mı ? bool bir değer döndür.
                //System.IO.File.Exists(fullFileName);
            }

            return(RedirectToAction("FileManager"));
        }
Beispiel #5
0
        public void TestConstructor()
        {
            var method = new MediaUpload(JsonReader.Parse(SampleInsertMethod) as JsonDictionary);

            Assert.That(method.MaxSize, Is.Not.Null);
            Assert.That(method.MaxSize, Is.EqualTo("10GB"));
        }
Beispiel #6
0
        public void TestAccepts()
        {
            var method = new MediaUpload(JsonReader.Parse(SampleInsertMethod) as JsonDictionary);

            Assert.That(method.Accepts, Is.Not.Null);
            Assert.That(method.Accepts.Length, Is.EqualTo(3));
            Assert.That(method.Accepts, Is.EquivalentTo(
                            new string[] { "image/*", "video/*", "audio/*" }));
        }
        public async Task <string> UploadStreamAsync(string containerPath, MediaUpload media)
        {
            var blockBlob = await GetBlockBlobAsync(containerPath, media.FileName);

            media.File.Position = 0;
            await blockBlob.UploadFromStreamAsync(media.File);

            return(blockBlob.StorageUri?.PrimaryUri.AbsoluteUri);
        }
    private MediaUpload mu;         // reference to Media Upload component, attached dynamically at runtime


    #region UNITY_EVENT_FUNCTIONS

    /// <summary>
    /// General Start routine.
    /// </summary>
    void Start()
    {
        // attach a new component of type MediaUpload to this GameObject
        mu = this.gameObject.AddComponent <MediaUpload>();

        // configure MediaUpload component
        mu.cnfgSrvr_uploadURL             = "https://USER_SERVER_URL:USER_PORT/umu/uploadbinarydata";
        mu.cnfgSrvr_sessionNameTimeFormat = "yyyy-MM-dd_HH-mm-ss";
        //mu.cnfgSrvr_isAllowedToConnect = false;

        // initialize MediaUpload component
        bool muIsInitialized = mu.init();
    }
Beispiel #9
0
        public void TestProtocols()
        {
            var method = new MediaUpload(JsonReader.Parse(SampleInsertMethod) as JsonDictionary);

            Assert.That(method.Simple, Is.Not.Null);
            Assert.That(method.Simple.MultiPart, Is.True);
            Assert.That(method.Simple.Path, Is.Not.Null);
            Assert.That(method.Simple.Path, Is.EqualTo("/upload/test/v4/resources"));

            Assert.That(method.Resumable, Is.Not.Null);
            Assert.That(method.Resumable.MultiPart, Is.True);
            Assert.That(method.Resumable.Path, Is.Not.Null);
            Assert.That(method.Resumable.Path, Is.EqualTo("/resumable/upload/test/v4/resources"));
        }
Beispiel #10
0
        MediaUpload UploadSaveToDatabase(HttpPostedFileBase img)
        {
            string uniqueFileName = Guid.NewGuid().ToString();
            string extention      = Path.GetExtension(img.FileName);
            string fullFileName   = HttpContext.Server.MapPath("/Media/Images/" + uniqueFileName + extention);

            img.SaveAs(fullFileName);
            MediaUpload upload = new MediaUpload();

            upload.Name = uniqueFileName + extention;
            upload.Path = "/Media/Images/" + uniqueFileName + extention;

            return(upload);
        }
        public Task <bool> SaveUploadAsync(MediaUpload model)
        {
            return(Task.Run(() =>
            {
                _uow.GetRepo <MediaUpload>()
                .Add(model);

                if (_uow.Commit() > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }));
        }
Beispiel #12
0
        public async Task Shoud_Upload_Image()
        {
            /* Setup */
            var fileUpload = new MediaUpload
            {
                Product =
                {
                    Identifier = "boxer-tel-0m-0m",
                    Attribute  = "Product_Image_Medium"
                },
                FilePath = "C:\\tmp\\product_logo.png"
            };

            /* Test */
            var response = await Client.UploadAsync(fileUpload);

            /* Assert */
        }
Beispiel #13
0
        public ActionResult UploadMedia(MediaUpload model)
        {
            if (Session["User"] == null)
            {
                return(Content("login"));
            }
            int UserId = ((Urdu_Magazine.Models.User)Session["User"]).id;

            if (ModelState.IsValid)
            {
                Dictionary <bool, string> uploadResults = uploadMediaFiles(model.Image);
                string result;
                if (uploadResults == null)
                {
                    return(Content("Cannot create directory."));
                }
                else if (uploadResults.TryGetValue(false, out result))
                {
                    ModelState.AddModelError(result, "Cannot upload this file. Try Again.");
                }
                else if (uploadResults.TryGetValue(true, out result))
                {
                    var         fileNameAndImagePath = result.Split('>');
                    UploadMedia uploadMedia          = new UploadMedia
                    {
                        imgName     = model.Name,
                        userId      = UserId,
                        imgFileName = fileNameAndImagePath[0],
                        imgPath     = fileNameAndImagePath[1]
                    };

                    db.UploadMedias.Add(uploadMedia);
                    db.SaveChanges();
                    return(Json(new
                    {
                        message = "success",
                        Id = uploadMedia.Id,
                        file = uploadMedia.imgName,
                        path = uploadMedia.imgPath
                    }, JsonRequestBehavior.AllowGet));
                }
            }
            return(Content("failed"));
        }
        private async void UploadUserImage(object obj)
        {
            _media = new MediaUpload();
            string type = obj.ToString();

            if (type == "banner")
            {
                flag   = true;
                Banner = await _media.PickPhoto();

                Visibility = true;
            }
            else if (type == "ProfileImage")
            {
                ProfileImage = await _media.PickPhoto();

                Visibility = true;
            }
        }
        public ActionResult MediaMetadata(MediaUpload mediaUpload, HttpPostedFileBase file)
        {
            try
            {
                if (file.ContentLength > 0)
                {
                    var uploadedMedia = new UploadedMedia();
                    uploadedMedia.FileName    = file.FileName;
                    uploadedMedia.Length      = file.ContentLength;
                    uploadedMedia.ContentType = file.ContentType;

                    using (var reader = new System.IO.BinaryReader(file.InputStream))
                    {
                        uploadedMedia.Stream = reader.ReadBytes(file.ContentLength);

                        this._mediaUploadService.Process(uploadedMedia, mediaUpload.DataClassification);
                        ViewBag.Message = "File Uploaded Successfully!!";

                        if (StringComparer.InvariantCultureIgnoreCase.Compare(mediaUpload.SomeCustomData,
                                                                              "Directory") == 0)
                        {
                            long check = file.InputStream.Position;
                            //Rewind:
                            file.InputStream.Position = 0;
                            //_studentRawImportService.Do(file.InputStream);
                        }
                        //Place Using outside of Do, as it will close the underlying Stream (not good)
                    }
                }
                else
                {
                    ViewBag.Message = "No file uploaded.";
                }

                return(View());
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return(View());
            }
        }
Beispiel #16
0
 public ActionResult Guncelle(PostViewModel model)
 {
     if (model.Post != null)
     {
         if (model.PostedPic != null)
         {
             MediaUpload m = new MediaUpload();
             m = UploadSaveToDatabase(model.PostedPic);
             _uow.GetRepo <MediaUpload>()
             .Add(m);
             model.Post.PostPic = m.Path.ToString();
         }
         _uow.GetRepo <Post>()
         .Update(model.Post);
         if (_uow.Commit() > 0)
         {
             return(RedirectToAction("Listele", "Post"));
         }
     }
     return(RedirectToAction("Listele", "Post"));
 }
        public ActionResult Upload(IEnumerable <HttpPostedFileBase> items)
        {
            MediaUpload media = new MediaUpload();

            foreach (HttpPostedFileBase item in items)
            {
                string uniqueFileName = Guid.NewGuid().ToString();
                string extention      = Path.GetExtension(item.FileName);
                string fullFileName   = HttpContext.Server.MapPath("/Media/Images/" + uniqueFileName + extention);
                item.SaveAs(fullFileName);
                media.Name = uniqueFileName + extention;
                media.Path = "/Media/Images/" + uniqueFileName + extention;

                _uow.GetRepo <MediaUpload>()
                .Add(media);
            }
            try
            {
                if (_uow.Commit() > 0)
                {
                    return(RedirectToAction("FileManager"));
                }
                else
                {
                    TempData["Msg"] = "Bir hata oluştu!";
                    return(View());
                }
            }
            catch (Exception ex)
            {
                _log.ProgramLogging(ex.Message);

                _uow.Commit();
                TempData["Msg"] = "Bir hata oluştu!";
                return(View());
            }
        }
Beispiel #18
0
        public void Run(Item processor, Item itemToProcess, Item fieldMapping)
        {
            ImportConfig   config         = new ImportConfig(fieldMapping.Parent.Parent, fieldMapping.Database, "");
            Uri            baseUri        = new Uri(config.BaseUrl);
            BaseMapping    baseMap        = new BaseMapping(fieldMapping);
            MediaProcessor mediaProcessor = new MediaProcessor(processor);
            HtmlDocument   document       = new HtmlDocument();
            string         content        = itemToProcess.Fields[baseMap.NewItemField].Value;

            document.LoadHtml(content);

            using (new SecurityModel.SecurityDisabler())
            {
                foreach (var mediaType in mediaProcessor.MediaTypes)
                {
                    var nodes = document.DocumentNode.SelectNodes(string.Format("//{0}/@{1}", mediaType.Identifier, mediaType.Attribute));
                    if (nodes == null)
                    {
                        continue;
                    }

                    //select nodes in html where path ends with extension listed in config
                    List <HtmlNode> targetedNodes = nodes.Where(n => n.Attributes[mediaType.Attribute].Value.Trim().ToLower()
                                                                .EndsWith(mediaType.Extension.Trim().ToLower())).ToList();

                    if (targetedNodes == null)
                    {
                        targetedNodes = nodes.Where(n => n.Attributes[mediaType.Attribute].Value.Trim().ToLower()
                                                    .Contains(mediaType.Extension.Trim().ToLower())).ToList();
                    }
                    else
                    {
                        targetedNodes.AddRange(nodes.Where(n => n.Attributes[mediaType.Attribute].Value.Trim().ToLower()
                                                           .Contains(mediaType.Extension.Trim().ToLower())).ToList());
                    }


                    foreach (var child in targetedNodes)
                    {
                        try
                        {
                            //Make sure the selected tags have media items to import, with existing parameters to follow
                            string source         = child.Attributes[mediaType.Attribute].Value;
                            string mediaExtension = Path.GetExtension(source);
                            if (string.IsNullOrEmpty(source))
                            {
                                continue;
                            }


                            Uri mediaSource = new Uri(source, UriKind.RelativeOrAbsolute);

                            if (mediaSource.IsAbsoluteUri)
                            {
                                if ((mediaSource.Host != baseUri.Host))
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                //This is for internal/relative path images
                                mediaSource = new Uri(baseUri, source);
                            }

                            string destination = mediaProcessor.RetrieveDestination(processor, mediaProcessor.RootDestination, source, mediaSource, baseUri);

                            Item importedMediaItem = MediaUpload.UploadMedia(mediaSource.ToString(), destination, itemToProcess);

                            if (importedMediaItem != null)
                            {
                                var mediaUrl = "-/media/" + importedMediaItem.ID.ToShortID().ToString() + ".ashx";

                                //Swap the old link with the new link to our media library
                                HtmlNode newChild = child.Clone();
                                newChild.Attributes[mediaType.Attribute].Value = mediaUrl;
                                content = content.Replace(child.OuterHtml, newChild.OuterHtml);

                                itemToProcess.Editing.BeginEdit();
                                itemToProcess.Fields[baseMap.NewItemField].Value = content;
                                itemToProcess.Editing.EndEdit();
                                ImportReporter.Write(itemToProcess, Level.Info, string.Format("Link updated for: {0}", importedMediaItem.Name), baseMap.NewItemField, "Media Importer");
                            }
                        }
                        catch (Exception ex)
                        {
                            ImportReporter.Write(itemToProcess, Level.Error, string.Format("There was an error importing media from {0}. Error: {1}.", string.Concat(baseUri, child.Attributes[mediaType.Attribute].Value), ex.Message), baseMap.NewItemField, "Media Import");
                            //Error importing media and/or updating links to media
                        }
                    }
                }
            }
        }
Beispiel #19
0
        public ActionResult Ekle(PostViewModel model)
        {
            if (model.PostedPic != null)
            {
                #region UploadPhotoSaveToDatabase
                MediaUpload upload = new MediaUpload();
                upload = UploadSaveToDatabase(model.PostedPic);
                _uow.GetRepo <MediaUpload>()
                .Add(upload);
                _uow.Commit();
                model.Post.PostPic = upload.Path.ToString();
                #endregion
            }

            if (model.Post.Tags != null)
            {
                char[] separators = { ',', '.', '!', '?', ';', ':', ' ' };
                tags = model.Post.Tags.Split(separators);
            }

            IsSuccess = false;
            var validator = new PostAddValidator().Validate(model.Post);
            if (validator.IsValid)
            {
                if (model.Post.Tags != null)
                {
                    foreach (var item in tags)
                    {
                        model.Post.Tags = item.ToString();
                    }
                }
                model.Post.UserId   = 1;
                model.Post.PostDate = DateTime.Now;
                _uow.GetRepo <Post>()
                .Add(model.Post);

                #region KategoriGönderiSayısıKontrol
                _uow.GetRepo <Category>()
                .GetById(model.Post.CategoryId)
                .PostCount++;
                #endregion

                if (_uow.Commit() > 0)
                {
                    IsSuccess         = true;
                    ViewBag.IsSuccess = IsSuccess;
                    ViewBag.Msg       = "Yazı başarıyla eklendi.";
                }
                else
                {
                    ViewBag.IsSuccess = IsSuccess;
                    ViewBag.Msg       = "Yazı kaydedilirken bir hata oluştu!";
                }
            }
            else
            {
                validator.Errors.ToList().ForEach(x => ModelState.AddModelError(x.PropertyName, x.ErrorMessage));
            }
            CategoryFill();
            return(View());
        }
 public TweetPageViewModel()
 {
     _media = new MediaUpload();
 }
Beispiel #21
0
        /// <summary>
        /// 上传临时素材
        /// </summary>
        private void TemporaryMeidaUpload()
        {
            //返回格式:{"status":"error,success,warning","msg":""}

            // string result = "{\"status\":\"{0}\",\"msg\":\"{1}\"}";



            try
            {
                //根据前台html的name获取文件
                HttpPostedFile upfile = _httpContext.Request.Files["file_temporaryImage"];

                if (upfile == null)
                {
                    ResponseWriteEnd(status.warning.ToString(), "没有选择文件");
                }

                //文件原名称
                string oldMediaName = upfile.FileName;

                //文件后辍名称
                string oldMediaExtension = Path.GetExtension(oldMediaName);

                //判断文件格式是否符合要求
                if (!oldMediaExtension.ToLower().Equals(".jpg"))
                {
                    ResponseWriteEnd(status.warning.ToString(), "请上传jpg格式的文件!");
                    return;
                }

                //判断文件大小是否符合要求
                if (upfile.ContentLength >= (1024 * 1024 * 1))
                {
                    ResponseWriteEnd(status.warning.ToString(), "请上传1M以内的文件!");
                    return;
                }

                string imgName = DateTime.Now.ToString("yyyy-MM-dd-HH-ss") + DateTime.Now.Ticks;
                bool   flag    = false;

                try
                {
                    upfile.SaveAs(_httpContext.Server.MapPath("/Upload/" + imgName + ".jpg"));
                    flag = true;
                }
                catch (Exception e)
                {
                    //写入日志
                }

                if (flag)
                {
                    //返回json
                    string mediaIdJson =
                        new MediaUpload().GetTemporaryMediaId(_commonClass.Get_access_token(_weiXinConfiguration, "catch"), _httpContext.Server.MapPath("/Upload/" + imgName + ".jpg"));

                    _debugLog.BugWriteTxt(_log.LogTxtPhyPath, "临时素材:" + mediaIdJson);

                    ResponseWriteEnd(status.success.ToString(), "/Upload/" + imgName + ".jpg", mediaIdJson);
                }
                else
                {
                    File.Delete(_httpContext.Server.MapPath("/Upload/" + imgName + ".jpg"));

                    ResponseWriteEnd(status.warning.ToString(), "图片保存出错,已经被删除。");
                }
            }
            catch (Exception EX_NAME)
            {
                ResponseWriteEnd(status.error.ToString(), EX_NAME.ToString());
            }
        }
Beispiel #22
0
        internal AddMediaResponse AddMedia(string url, string linkid, int TypeId, int MediaContext, string saediFromid, MediaUpload mediaresult)
        {
            AddMediaResponse media = new AddMediaResponse();

            try
            {
                media = AddMediaMapping(url, linkid, TypeId, MediaContext, saediFromid, mediaresult);
            }
            catch (Exception ex)
            {
                onlineBookingLogBLL.InsertOnlineServiceLog("AddMedia info to cs", ex.Message.ToString(), saediFromid, url, false);
            }

            return(media);
        }
Beispiel #23
0
        private AddMediaResponse AddMediaMapping(string url, string linkid, int TypeId, int MediaContext, string saediFromid, MediaUpload mediaresult)
        {
            AddMediaResponse mediaresponse = new AddMediaResponse();

            onlineClient.Url = url;
            TMedia tmedia = new TMedia();

            tmedia.MSGUID         = mediaresult.mediauploadResponse.MSGUID;
            tmedia.TypeID         = mediaresult.mediauploadRequest.TypeID;
            tmedia.MediaTimeStamp = mediaresult.mediauploadRequest.TimeStamp;
            tmedia.MediaText      = mediaresult.mediauploadRequest.Notes;
            tmedia.MediaSubject   = mediaresult.mediauploadRequest.Notes;
            tmedia.MediaPrivateFg = mediaresult.mediauploadRequest.MediaPrivateFg;
            tmedia.MediaExtension = mediaresult.mediauploadRequest.MediaExtension;
            tmedia.MediaContext   = mediaresult.mediauploadRequest.ContextID;
            tmedia.FileName       = mediaresult.mediauploadRequest.FileName;
            tmedia.LinkID         = mediaresult.mediauploadRequest.LinkId;


            TAddMediaResponse mediaResponse = onlineClient.AddMedia(tmedia);

            //mapping media
            onlineBookingLogBLL.InsertOnlineServiceLog(tmedia, mediaResponse, saediFromid, url, mediaResponse.ErrorCode != 0);


            mediaresponse.ErrorCode = mediaResponse.ErrorCode;
            mediaresponse.ErrorText = mediaResponse.ErrorText;



            return(mediaresponse);
        }