Exemple #1
0
        public async Task <IHttpActionResult> UploadPhoto(bool saveToTemporary = true)
        {
            var    file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
            string path = string.Empty;

            string      userId      = User.Identity.GetUserId();
            UploadImage uploadImage = new UploadImage(userId);

            if (file != null)
            {
                if (!saveToTemporary)
                {
                    path = UploadImageProperties.ImageUserFolder;
                }

                UploadImageResult result = await uploadImage.ImageCropAndResize(file, w : UploadImageProperties.ImageSmallResize, h : UploadImageProperties.ImageSmallResize, path : path);

                if (!String.IsNullOrEmpty(result.Error))
                {
                    ModelState.AddModelError("Upload", result.Error);
                    return(BadRequest(ModelState));
                }

                var adress = UploadImageProperties.BlobAdress + result.PathFile;
                return(Ok(adress));
            }
            else
            {
                ModelState.AddModelError("FileError", "File was not received by the server");
                return(BadRequest(ModelState));
            }
        }
Exemple #2
0
        protected void rptAllNews_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "btnGuncelle")
            {
                int        HeadlineId = Convert.ToInt32(e.CommandArgument);
                TextBox    txtTitle   = (TextBox)e.Item.FindControl("txtTitle");
                TextBox    txtSummary = (TextBox)e.Item.FindControl("txtSummary");
                TextBox    txtUrl     = (TextBox)e.Item.FindControl("txtUrl");
                FileUpload fuGorsel   = (FileUpload)e.Item.FindControl("fuGorsel");
                CheckBox   cbStatus   = (CheckBox)e.Item.FindControl("cbStatus");

                if (fuGorsel.HasFile)
                {
                    string      folder         = ConfigurationManager.AppSettings["HeadlineImagePath"] + @"\" + Helper.GetDirectory();
                    string      image          = "";
                    Bitmap      imageBitMap    = new Bitmap(fuGorsel.PostedFile.InputStream);
                    UploadImage uploadHeadline = new UploadImage();
                    //uploadHeadline.SaveImageSingle(imageBitMap, Server.MapPath(folder), HeadlineId + "_" + Path.GetExtension(fuGorsel.FileName), 640, 360);
                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }

                    image = folder + HeadlineId + "_640_360" + Path.GetExtension(fuGorsel.FileName);
                    uploadHeadline.SaveImageSingle(imageBitMap, folder + "/", HeadlineId + "_640_360" + Path.GetExtension(fuGorsel.FileName), 640, 360);
                    //HeadlinesOprt.UpdateHeadline(txtUrl.Text, txtTitle.Text, txtSummary.Text, image, Convert.ToInt32(cbStatus.Checked), HeadlineId.ToString());
                }
                else
                {
                    //HeadlinesOprt.UpdateHeadline(txtUrl.Text, txtTitle.Text, txtSummary.Text, Convert.ToInt32(cbStatus.Checked), HeadlineId.ToString());
                }
            }
            GetData();
        }
Exemple #3
0
        protected void ButtonSubmit_Click(object sender, EventArgs e)
        {
            if (Validation())
            {
                string  id  = Session["ArtID"].ToString();
                Article art = new Article();
                art = art.GetArticleById(id);

                String title       = TextboxTitle.Text.ToString();
                String description = TextboxDescription.Text.ToString();
                var    dateAndTime = DateTime.Now;
                String lastupdated = dateAndTime.ToShortDateString();
                String link        = TextboxLink.Text.ToString();
                String image       = "";

                if (UploadImage.HasFile)
                {
                    string filename = Path.GetFileName(UploadImage.FileName);
                    UploadImage.SaveAs(Server.MapPath("img/articleImages/") + filename);
                    image = ("img/articleImages/" + filename);
                }
                else
                {
                    image = art.Image;
                }

                //Get Article

                art = art.GetArticleById(id);
                int insCnt = art.UpdateArticle(id, title, description, image, link, lastupdated);
                Response.Redirect("LearnAdmin.aspx");
            }
        }
Exemple #4
0
 /// <summary>
 /// 修改按钮
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void btnSubmit_Click(object sender, EventArgs e)
 {
     if (this.textEmail.Text != "" && this.textNickName.Text != "" && this.textPassword.Text != "" && this.textID.Text != "")
     {
         UploadImage ui        = new UploadImage();
         var         id        = Request.Params["Id"];
         var         PhotoName = ub.Get_UserPhoto(Convert.ToInt32(id));
         UsersModels u         = new UsersModels()
         {
             ID       = int.Parse(this.textID.Text),
             Email    = this.textEmail.Text,
             NickName = this.textNickName.Text,
             Password = this.textPassword.Text,
             // Photo = ui.UpFileName2(this.FileUpload1, "~/User_folder/"),
         };
         if (ub.Up_User(u))
         {
             Response.Write(s: "<script>alert('修改成功');location.href='UsersManager.aspx'</script>");
         }
         else
         {
             Response.Write(s: "<script>alert('修改失败');location.href='UsersManager.aspx'</script>");
         }
     }
     else
     {
         Response.Write("<script>alert('没有信息');</script>");
     }
 }
Exemple #5
0
        public ActionResult Edit(AppUser kullanici, HttpPostedFileBase image)
        {
            AppUser orjinalUser = userRepo.Find(kullanici.ID);

            if (orjinalUser != null)
            {
                orjinalUser.Name         = kullanici.Name;
                orjinalUser.SurName      = kullanici.SurName;
                orjinalUser.UserName     = kullanici.UserName;
                orjinalUser.BirthDate    = kullanici.BirthDate;
                orjinalUser.EmailAddress = kullanici.EmailAddress;

                orjinalUser.ProfilePicturePath = UploadImage.ImageAdd(image, "/UserImages/");

                if (orjinalUser.ProfilePicturePath == "0" || orjinalUser.ProfilePicturePath == "1")
                {
                    orjinalUser.ProfilePicturePath = "/ProductImages/user.png";
                }

                orjinalUser.Role     = kullanici.Role;
                orjinalUser.Password = kullanici.Password;
                userRepo.Update(orjinalUser);
            }
            else
            {
                TempData["HataMesaji"] = "Kullanıcı Bulunamadı";
            }
            return(RedirectToAction("Index", "Appuser", new { area = "Admin" }));
        }
Exemple #6
0
        public string UploadImage(byte[] msgArray, string user_id, string display_name)
        {
            var    today    = timeService.GetLocalDateTime(LocalTimeService.CHINA_STANDARD_TIME);
            var    client   = new ImgurClient(IMGUR_CLIENT_ID, IMGUR_CLIENT_SECRET);
            var    endpoint = new ImageEndpoint(client);
            IImage image;

            Stream stream = new MemoryStream(msgArray);

            using (stream)
            {
                image = endpoint.UploadImageStreamAsync(stream).GetAwaiter().GetResult();
            }
            using (var db = new LineModel())
            {
                var instance = new UploadImage
                {
                    addTime  = today,
                    flg      = false,
                    imageUrl = image.Link,
                    userId   = user_id,
                    userName = display_name
                };
                db.UploadImage.Add(instance);
                db.SaveChanges();

                var status = db.UploadStatus.Where(x => x.UserId == user_id && x.CommandStr == "--upload").ToList();
                db.UploadStatus.RemoveRange(status);

                db.SaveChanges();
            }
            return(image.Link);
        }
Exemple #7
0
        /// <summary>
        /// Creates the Upload Image object to pass to the webview
        /// from an Android Uri
        /// </summary>
        public static UploadImage CreateUploadImageNoData(int index, Context context, Android.Net.Uri uri)
        {
            var fileName = GetFileName(context, uri);
            var image    = new UploadImage(index, fileName);

            return(image);
        }
Exemple #8
0
        public static void UploadFilesToServer(Uri uri, Dictionary <string, string> data, string fileName, string fileContentType, byte[] fileData)
        {
            string         boundary       = "----------" + DateTime.Now.Ticks.ToString("x");
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            httpWebRequest.Method      = "POST";
            httpWebRequest.BeginGetRequestStream((result) => {
                try {
                    HttpWebRequest request = (HttpWebRequest)result.AsyncState;
                    using (Stream requestStream = request.EndGetRequestStream(result)) {
                        UploadImage.WriteMultipartForm(requestStream, boundary, data, fileName, fileContentType, fileData);
                    }
                    request.BeginGetResponse(a => {
                        try {
                            var response       = request.EndGetResponse(a);
                            var responseStream = response.GetResponseStream();
                            using (var sr = new StreamReader(responseStream)) {
                                using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) {
                                    string responseString = streamReader.ReadToEnd();
                                    // do shit here?
                                }
                            }
                        }
                        catch (Exception) {
                        }
                    }, null);
                }
                catch (Exception) {
                }
            }, httpWebRequest);
        }
Exemple #9
0
        public async Task <HttpResponseMessage> Save()
        {
            //todo
            if (!Request.Form.Files.Any())
            {
                UploadImage model = new UploadImage();
                foreach (string kvp in Request.Form.Keys)
                {
                    PropertyInfo pi = model.GetType().GetProperty(kvp, BindingFlags.Public | BindingFlags.Instance);
                    if (pi != null)
                    {
                        pi.SetValue(model, Request.Form[kvp], null);
                    }
                }

                foreach (var formFileTemp in Request.Form.Files)
                {
                    if (formFileTemp.Length > 0)
                    {
                        var filePath = Path.GetTempFileName();

                        using (var stream = System.IO.File.Create(filePath))
                        {
                            await formFileTemp.CopyToAsync(stream);
                        }
                    }
                }
            }

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
        // GET: UserHome/Details/5
        public ActionResult Details(int id)
        {
            UploadImage image = new UploadImage();

            image = db.UploadImages.Where(x => x.UploadImageID == id).FirstOrDefault();
            return(View(image));
        }
Exemple #11
0
        private async Task <BitmapImage> SetImageSource(UploadImage file)
        {
            BitmapImage bitmapImage = new BitmapImage();

            try
            {
                if (!file.ContentType.Contains("image"))
                {
                    var         uri      = @"ms-appx:///Assets/documentType/blank.png";
                    StorageFile tempFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(uri));

                    var tempStream = await tempFile.OpenReadAsync();

                    await bitmapImage.SetSourceAsync(tempStream);
                }
                else
                {
                    bitmapImage = new BitmapImage(new Uri(App.RootBaseUri + "File/" + file.Id));
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            return(bitmapImage);
        }
Exemple #12
0
        public async Task <IActionResult> Edit(int id, IFormFile imgUrl1, [Bind("Id,StudentId,FirstName,LastName,EnrollmentDate,AcquiredCredits,CurrentSemestar,EducationLevel")] Student student)
        {
            if (id != student.Id)
            {
                return(NotFound());
            }
            UploadImage uploadImage = new UploadImage(WebHostEnvironment);

            student.ImageUrl = uploadImage.UploadedFile(imgUrl1);

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(student);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!StudentExists(student.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(student));
        }
Exemple #13
0
    void GetAllImages()
    {
        texture2Ds.Clear();
        savedImages.Clear();
        DirectoryInfo dir = new DirectoryInfo(s);

        for (int i = 0; i < content.transform.childCount; i++)
        {
            Destroy(content.transform.GetChild(i));
        }
        info = dir.GetFiles("*.png");
        foreach (FileInfo f in info)
        {
            Debug.Log(f.Name);
            Texture2D texture = UploadImage.LoadPNG(s + f.Name);
            texture2Ds.Add(texture);
            GameObject g = Instantiate(savedImage, new Vector3(0, 0, 0), Quaternion.identity);
            g.transform.parent = content.transform;

            Image image = g.transform.GetComponent <Image>();
            g.GetComponent <Button>().onClick.AddListener(delegate
            {
                SetFrameTexture(texture);
            });
            Rect rec = new Rect(0, 0, texture.width, texture.height);
            image.sprite = Sprite.Create(texture, rec, new Vector2(0, 0), 1);

            savedImages.Add(g);
        }
    }
Exemple #14
0
        public long SaveInspectionImg(int newMeasurePointId, UploadImage image)
        {
            ////////////////////////////////////
            // MEASUREPOINT_RECORD_IMAGES
            DAL.MEASUREPOINT_RECORD_IMAGES record = new DAL.MEASUREPOINT_RECORD_IMAGES();

            // FK ID
            record.MeasurePointRecordId = newMeasurePointId;

            // FileName
            byte[] imageData = GetUploadImageData(image.ImageFileName);
            record.Data = imageData;

            // Comment
            record.Comment = image.ImageComment;

            // Title
            record.Title = image.ImageTitle;

            // INSERT
            _MEASUREPOINT_RECORD_IMAGES.Add(record);
            _context.SaveChanges();

            return record.Id;
        }
Exemple #15
0
        public Boolean SaveEquipmentImages(UploadImage item)
        {
            DAL.INSPECTION_MANDATORY_IMAGES record = new DAL.INSPECTION_MANDATORY_IMAGES();

            // FK ID
            record.CustomerModelMandatoryImageId = item.ServerId;

            // FK ID
            record.InspectionId = _InspectionAuto;

            // FileName
            byte[] image = GetUploadImageData(item.ImageFileName);
            record.Data = image;

            // Comment
            record.Comment = item.ImageComment;

            // Title
            record.Title = item.ImageTitle;

            // Side
            record.Side = 0;

            // INSERT
            _INSPECTION_MANDATORY_IMAGES.Add(record);

            return true;
        }
        public IActionResult UploadImage(UploadImage uploadedImage, [FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return(View(uploadedImage));
            }

            var image = uploadedImage.Image;

            byte[] imageData = null;
            using (var binaryReader = new BinaryReader(image.OpenReadStream()))
            {
                imageData = binaryReader.ReadBytes((int)image.Length);
            }

            var imageForDb = ImageHelper.AddOleHeader(imageData);

            var category = _categoryService.GetCategoryById(id);

            category.Picture = imageForDb;

            var result = _categoryService.UpdateCategory(category);

            if (result == false)
            {
                return(RedirectToAction("Error", "Home"));
            }

            return(RedirectToAction("Index"));
        }
 public UserViewModel()
 {
     _bitmapImage = new BitmapImage();
     _uploadImage = new UploadImage();
     _conn        = new Connections();
     ResetUsers();
 }
        public async Task <IActionResult> Edit(int id, [Bind("ImageId,ImageFile,ImageName,ImageDescription,UserId")] UploadImage uploadImage)
        {
            if (id != uploadImage.ImageId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(uploadImage);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UploadImageExists(uploadImage.ImageId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["UserId"] = new SelectList(_context.ApplicationUsers, "Id", "Id", uploadImage.UserId);
            return(View(uploadImage));
        }
        public ActionResult saveHead()
        {
            var         user  = CheckLogin.Instance.GetUser();
            UploadImage model = new UploadImage();

            model.HeadFileName = Request.Form["HeadFileName"].ToString();
            model.X            = Convert.ToInt32(Request.Form["X"]);
            model.X            = Convert.ToInt32(Request.Form["Y"]);
            model.Width        = Convert.ToInt32(Request.Form["Width"]);
            model.Height       = Convert.ToInt32(Request.Form["Height"]);
            model.UserID       = user.ID;
            if ((model == null))
            {
                return(Json(new { msg = 0 }));
            }
            else
            {
                var    filepath = Path.Combine(Server.MapPath("~/UploadFiles/temp"), model.HeadFileName);
                string fileExt  = Path.GetExtension(filepath);
                Random r        = new Random();
                var    filename = DateTime.Now.ToString("yyyyMMddHHmmss") + r.Next(10000) + fileExt;
                var    path180  = Path.Combine(Server.MapPath("~/UploadFiles/180"), filename);
                var    path75   = Path.Combine(Server.MapPath("~/UploadFiles/75"), filename);
                var    path50   = Path.Combine(Server.MapPath("~/UploadFiles/50"), filename);
                var    path25   = Path.Combine(Server.MapPath("~/UploadFiles/25"), filename);
                cutAvatar(filepath, model.X, model.Y, model.Width, model.Height, 75L, path180, 180);
                cutAvatar(filepath, model.X, model.Y, model.Width, model.Height, 75L, path75, 75);
                cutAvatar(filepath, model.X, model.Y, model.Width, model.Height, 75L, path50, 50);
                cutAvatar(filepath, model.X, model.Y, model.Width, model.Height, 75L, path25, 25);
                unitOfWork.UploadImageRepository.Insert(model);
                unitOfWork.Save();
                return(Json(new { msg = 1 }));
            }
        }
Exemple #20
0
        public async Task <HttpResponseMessage> DeleteImageByName(int siteID, int programID, int tracerCustomID, int tracerQuestionID, int tracerResponseID, int userID, string imageName)
        {
            try
            {
                //   TracerServices service = new TracerServices();


                var        container = UploadImage.azureContainer();
                ICloudBlob _blockBlob;
                //delete blob from container

                //delete Actual Image
                _blockBlob = await container.GetBlobReferenceFromServerAsync("Actual/" + siteID + "/" + programID + "/" + tracerCustomID + "/" + imageName);

                _blockBlob.Delete();
                //delete Thumb Image
                _blockBlob = await container.GetBlobReferenceFromServerAsync("Thumb/" + siteID + "/" + programID + "/" + tracerCustomID + "/" + imageName);

                _blockBlob.Delete();


                tracerService.DeleteImageByImageName(tracerCustomID, tracerQuestionID, tracerResponseID, userID, imageName);

                return(Request.CreateResponse(HttpStatusCode.OK, "File Deleted"));
            }
            catch (Exception ex)
            {
                ex.Data.Add("tracerCustomId", tracerCustomID);
                ex.Data.Add("HTTPReferrer", "JCRAPI/Image/Delete");
                WebExceptionHelper.LogException(ex, null);
                return(null);
            }
        }
Exemple #21
0
        public bool AddUploadImage(UploadImage Model)
        {
            param.Add("[@AccountID],[" + Model.AccountID + "]");
            param.Add("[@PictureTypeId],[" + Model.PictureTypeId + "]");
            param.Add("[@UploadName],[" + Model.UploadName + "]");
            param.Add("[@PictureUrl],[" + Model.PictureUrl + "]");
            param.Add("[@UPloadTime],[" + Model.UPloadTime + "]");
            param.Add("[@AddressDifferent],[" + Model.AddressDifferent + "]");

            int num = 0;

            try
            {
                ws_mysql.Credentials = new System.Net.NetworkCredential(PublicConst.WS_USERNAME, PublicConst.WS_USERPWD);
                num = ws_mysql.ExecuteNonQuery(param.ToArray(), "", addSql, "dgm");
            }
            catch
            {
            }
            finally
            {
                param.Clear();
            }
            return(num > 0);
        }
Exemple #22
0
        /// <summary>
        /// 根据资金来源Id查询资金来源
        /// </summary>
        /// <param name="ClassesID"></param>
        /// <returns></returns>
        public UploadImage GetUploadImageByUploadImageId(string UploadImagesId)
        {
            UploadImage UploadImageInfo = null;

            param.Add("[@UploadimgId],[" + UploadImagesId + "]");

            try
            {
                ws_mysql.Credentials = new System.Net.NetworkCredential(PublicConst.WS_USERNAME, PublicConst.WS_USERPWD);
                DataSet myDataset = ws_mysql.ExecuteDataSet(param.ToArray(), "", selSql, "dgm");
                foreach (DataRow mDr in myDataset.Tables[0].Rows)
                {
                    UploadImageInfo                  = new UploadImage();
                    UploadImageInfo.UploadimgId      = UploadImagesId;
                    UploadImageInfo.AccountID        = mDr["AccountID"].ToString();
                    UploadImageInfo.PictureTypeId    = mDr["PictureTypeId"].ToString();
                    UploadImageInfo.UploadName       = mDr["UploadName"].ToString();
                    UploadImageInfo.PictureUrl       = mDr["PictureUrl"].ToString();
                    UploadImageInfo.UPloadTime       = mDr["UPloadTime"].ToString();
                    UploadImageInfo.AddressDifferent = mDr["AddressDifferent"].ToString();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                param.Clear();
            }
            return(UploadImageInfo);
        }
Exemple #23
0
        public async Task <NoteResponse> UploadImage(int noteID, string userID, IFormFile file)
        {
            try
            {
                var note = this.authenticationContext.Note.Where(s => s.UserID == userID && s.NoteID == noteID).FirstOrDefault();

                if (note != null && note.IsTrash == false)
                {
                    UploadImage imageUpload = new UploadImage(this.applicationSetting.APIkey, this.applicationSetting.APISecret, this.applicationSetting.CloudName);

                    var url = imageUpload.Upload(file);

                    note.Image        = url;
                    note.ModifiedDate = DateTime.Now;

                    this.authenticationContext.Note.Update(note);

                    await this.authenticationContext.SaveChangesAsync();

                    NoteResponse data = this.GetNoteResponse(userID, note);

                    return(data);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
        public ActionResult Edit(Product guncelUrun, HttpPostedFileBase image)
        {
            Product orjinalUrun = urunRepo.Find(guncelUrun.ID);

            if (orjinalUrun != null)
            {
                orjinalUrun.Name        = guncelUrun.Name;
                orjinalUrun.Price       = guncelUrun.Price;
                orjinalUrun.PicturePath = UploadImage.ImageAdd(image, "/ProductImages/");

                if (orjinalUrun.PicturePath == "0" || orjinalUrun.PicturePath == "1")
                {
                    orjinalUrun.PicturePath = "/ProductImages/user.png";
                }

                orjinalUrun.SubCategoryID = guncelUrun.SubCategoryID;
                orjinalUrun.UnitsInStock  = guncelUrun.UnitsInStock;

                urunRepo.Save();

                TempData["OnayMesaji"] = "Ürün Güncelleme Başarılı";
            }
            else
            {
                TempData["HataMesaji"] = "Ürün Güncelleme Sırasında Hata Oluştu";
            }

            return(RedirectToAction("Index", "Product", new { area = "Admin" }));
        }
        public async Task <IActionResult> Edit(int id, IFormFile imgUrl, [Bind("TeacherId,FirstName,LastName,Degree,AcademicRank,OfficeNumber,HireDate")] Teacher teacher)
        {
            if (id != teacher.TeacherId)
            {
                return(NotFound());
            }

            UploadImage uploadImage = new UploadImage(WebHostEnvironment);

            teacher.ImageUrl = uploadImage.UploadedFile(imgUrl);

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(teacher);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TeacherExists(teacher.TeacherId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(teacher));
        }
Exemple #26
0
        public RequestResponse <object> Delete([FromBody] UploadImage fileUrl)
        {
            var result = _storageHelper.Delete(fileUrl.FileName);

            return(new RequestResponse <object> {
                Success = result, Message = result ? FaceGraphConsts.SUCCESS_MESSAGE : FaceGraphConsts.ERROR_OCCURED_MESSAGE
            });
        }
        private void Upload_onBtnCaptureClick(object sender, EventArgs e)
        {
            UploadImage upload = (UploadImage)sender;

            tiempo_capture = upload.Tiempo_capture;
            uploadTemp     = upload;
            this.timer1.Start();
        }
Exemple #28
0
 public void SetSharedImageDataToUpload(UploadImage imageWithData)
 {
     Device.BeginInvokeOnMainThread(async() =>
     {
         var cmd = $"viewModel.uploadAndroidImageData({imageWithData});";
         await this.Browser.EvaluateJavaScriptAsync(cmd);
     });
 }
Exemple #29
0
        public ActionResult Index(FormCollection formCollection, string Option)
        {
            foreach (string item in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
                if (file.ContentLength == 0)
                {
                    continue;
                }

                if (file.ContentLength > 0)
                {
                    var upload      = new UploadImage();
                    var rename      = upload.RenameUploadFile(file);
                    var imageResult = upload.UploadFile(rename.File, rename.FileName);
                    if (imageResult.Success)
                    {
                        var iconGenerator = new IconGenerator();
                        if (!Option.IsNullOrWhiteSpace() && Option == "multiple")
                        {
                            var sizes = new List <int> {
                                57, 60, 72, 76, 114, 120, 114, 150, 152, 180, 192, 32, 96, 115
                            };
                            foreach (var size in sizes)
                            {
                                iconGenerator.CreateIcon(imageResult.FullPath, size, size, "_android.png");
                            }
                            foreach (var size in sizes)
                            {
                                iconGenerator.CreateIcon(imageResult.FullPath, size, size, "_apple.png");
                            }
                        }
                        else
                        {
                            iconGenerator.CreateIcon(imageResult.FullPath, 16, 16, ".ico");
                        }
                    }



                    if (imageResult.Success)
                    {
                        //TODO: write the filename to the db
                        Console.WriteLine(imageResult.ImageName);
                        ViewBag.Success  = "Image Successfully uploaded";
                        ViewBag.FileName = imageResult.ImageName;
                    }
                    else
                    {
                        //TODO: show view error
                        // use imageResult.ErrorMessage to show the error
                        ViewBag.Error = imageResult.ErrorMessage;
                    }
                }
            }

            return(View());
        }
        /// <summary>
        /// Gán url mới cho danh sách ảnh gửi lên Server
        /// </summary>
        /// <returns></returns>
        public async Task <bool> postMuiltiImage()
        {
            for (int i = 0; i < images.Count; ++i)
            {
                int index = i;
                if (!images[index].UriTmp.Equals("") || images[index].UriTmp != null)
                {
                    try
                    {
                        var client = new WebClientW();
                        client.UCEvent = (o) =>
                        {
                        };
                        client.UPCEvent = (o, e) =>
                        {
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                images[index].Progess = e * 0.1;
                            });
                        };
                        var indeximg  = images[index].UriTmp;
                        var uploadimg = new UploadImage {
                            token_id = 1, owner_id = account.Number_Id
                        };
                        var imageNews = await client.UploadMuitliImage(WebClientW.uploadServiceBaseAddress,
                                                                       images[index].UriTmp,
                                                                       new UploadImage { token_id = 1, owner_id = account.Number_Id });

                        images[index].UriImage = imageNews.UriImage;
                        images[index].Image_Id = imageNews.Image_Id;
                    }
                    catch (Exception ex)
                    {
                        var currentPage = AppChat.Helpers.Helper.Instiance().GetCurrentPage();
                        await currentPage.DisplayAlert("Lỗi up ảnh", ex.Message, "Ok");
                    }
                }
            }
            bool loop = true;

            while (loop)
            {
                loop = false;
                await Task.Delay(100);

                for (int i = 0; i < images.Count; i++)
                {
                    if (!images[i].UriImage.Equals("") || images[i].UriImage != null)
                    {
                        if (!images[i].UriImage.Contains("http"))
                        {
                            loop = true;
                        }
                    }
                }
            }
            return(loop);
        }
 public string UploadImg()
 {
     UploadImage ui = new UploadImage();
     ui.SetAllowSize = 1;
     ui.SetAllowFormat = ".jpeg,.jpg,.bmp,.gif,.png";//配在webConfig中
     string url = "/areas/formcontrol/views/_upload/temp/img/";
     string saveFolder = Server.MapPath(url);
     HttpPostedFile file = System.Web.HttpContext.Current.Request.Files[0];
     var reponseMessage = ui.FileSaveAs(file, saveFolder);
     return reponseMessage.ModelToJson();
 }
 public object Post(UploadImage request)
 {
  
     string urls = "";
     foreach (var uploadedFile in Request.Files.Where(uploadedFile => uploadedFile.ContentLength > 0))
     {
         var ms = new MemoryStream();
         {
             uploadedFile.WriteTo(ms);
             urls =WriteImage(ms);
              
         }
     }
     return new UploadImageResponse {Url = urls};
 }
        //发送图片文件
        private void sendSelfImage()
        {
            CSS.IM.Library.gifCollections tempGifs = PicQueue.Clone() as CSS.IM.Library.gifCollections;
            try
            {
                foreach (CSS.IM.Library.MyPicture pic in tempGifs)
                    if (pic.IsSent)
                    {
                        System.IO.FileInfo f = new System.IO.FileInfo(Util.sendImage + pic.ImageMD5 + ".gif");

                        //this.ImageTransfers(true, f.FullName, pic.ImageMD5, (int)f.Length, f.Extension, pic.ImageMD5);

                        FTPClient ftpClient = new FTPClient(Util.ServerAddress, Util.ftpPath, Util.ftpUser, Util.ftpPswd, Util.ftpPort);
                        ftpClient.FtpPath = XmppConn.MyJID.User;
                        UploadImage uploadImage = new UploadImage();
                        uploadImage.ftpClient = ftpClient;
                        uploadImage.ImageName = pic.ImageMD5;
                        uploadImage.Name = f.FullName;
                        uploadImage.parent = this;

                        Thread pushThread = new Thread(uploadImage.Upload);
                        pushThread.Start();

                        PicQueue.Romove(pic);//将richTextBox中的自定义图片清除掉,以便下次继续发送消息时出现再次发送的情况
                        //System.Threading.Thread.Sleep(500);
                    }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("发送图片时错误:" + ex.Message);
            }
        }