Beispiel #1
0
        public async Task <ActionResult <IEnumerable <FileResponseModel> > > Upload()
        {
            Microsoft.AspNetCore.Http.IFormFileCollection files = Request.Form.Files;
            string upload = Path.Combine(_hostEnvironment.ContentRootPath, UploadsFolder);

            if (!Directory.Exists(upload))
            {
                Directory.CreateDirectory(upload);
            }

            List <FileResponseModel> fileNames = new List <FileResponseModel>();

            foreach (Microsoft.AspNetCore.Http.IFormFile file in files)
            {
                if (file.Length > 0)
                {
                    string fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
                    string filePath = Path.Combine(upload, fileName);

                    using FileStream fileStream = new FileStream(filePath, FileMode.Create);
                    await file.CopyToAsync(fileStream);

                    fileNames.Add(new FileResponseModel {
                        FileName = fileName
                    });
                }
                else
                {
                    return(BadRequest());
                }
            }
            return(fileNames);
        }
Beispiel #2
0
        public List <dynamic> PersistImage(Microsoft.AspNetCore.Http.IFormFileCollection files)
        {
            if (files == null || files.Count == 0)
            {
                throw new ApplicationException("no files send to upload");
            }
            List <dynamic> lst = new List <dynamic>();

            using (var scope = ServiceActivator.GetScope())
            {
                UploadConfig uplConfig = (UploadConfig)scope.ServiceProvider.GetService(typeof(UploadConfig));
                string       dirpath   = GetDirectory(System.IO.Path.Combine(uplConfig.FullPath, GetCurrentTimeStamp(null)));
                files.ToList().ForEach(v =>
                {
                    var filepath = GetFile(System.IO.Path.Combine(dirpath, v.FileName));
                    using (var stream = new System.IO.FileStream(filepath, System.IO.FileMode.Create))
                        v.CopyTo(stream);
                    lst.Add(new
                    {
                        FileName    = System.IO.Path.GetFileName(filepath),
                        DownloadUrl = ""
                    });;
                });
            }
            return(lst);
        }
Beispiel #3
0
 public Upload(Microsoft.AspNetCore.Http.IFormFileCollection files, string uploadDir, bool Rename)
 {
     this.files     = files;
     this.uploadDir = uploadDir.Trim('\\');
     this.Extension = null;
     this.Rename    = Rename;
 }
Beispiel #4
0
 public Upload(Microsoft.AspNetCore.Http.IFormFileCollection files, string uploadDir, string[] Extension, bool Rename = true, int MaxFileCount = 5)
 {
     this.files        = files;
     this.uploadDir    = uploadDir.Trim('\\');
     this.Extension    = Extension;
     this.Rename       = Rename;
     this.MaxFileCount = MaxFileCount;
 }
Beispiel #5
0
        public async Task <IActionResult> EdiPost(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }


            MenuViewModel.MenuItem.SubCategoryID = Convert.ToInt32(Request.Form["SubCategoryID"].ToString());
            if (!ModelState.IsValid)
            {
                MenuViewModel.SubCategories = await dbContext.SubCategories.Where(s => s.CategoryID == MenuViewModel.MenuItem.CategoryID).ToListAsync();

                return(View(MenuViewModel));
            }

            //Saving Image Section

            string WebRootPath = hostingEnvironment.WebRootPath;

            Microsoft.AspNetCore.Http.IFormFileCollection files = HttpContext.Request.Form.Files;
            MenuItem menuItemFromDb = await dbContext.MenuItems.FindAsync(MenuViewModel.MenuItem.ID);

            if (files.Count > 0)

            {
                // New Image will  upload
                string uploads       = Path.Combine(WebRootPath, "images");
                string extension_new = Path.GetExtension(files[0].FileName);

                var imagepath = Path.Combine(WebRootPath, menuItemFromDb.Image.TrimStart('\\'));
                if (System.IO.File.Exists(imagepath))
                {
                    System.IO.File.Delete(imagepath);
                }
                //we will upload new file
                using (FileStream fileStream = new FileStream(Path.Combine(uploads, MenuViewModel.MenuItem.ID + extension_new), FileMode.Create))
                {
                    files[0].CopyTo(fileStream);
                }

                menuItemFromDb.Image = @"\images\" + MenuViewModel.MenuItem.ID + extension_new;
            }

            menuItemFromDb.Name          = MenuViewModel.MenuItem.Name;
            menuItemFromDb.Description   = MenuViewModel.MenuItem.Description;
            menuItemFromDb.Price         = MenuViewModel.MenuItem.Price;
            menuItemFromDb.Taste         = MenuViewModel.MenuItem.Taste;
            menuItemFromDb.CategoryID    = MenuViewModel.MenuItem.CategoryID;
            menuItemFromDb.SubCategoryID = MenuViewModel.MenuItem.SubCategoryID;


            await dbContext.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
        private string CreateImageFile(string webRootPath, Microsoft.AspNetCore.Http.IFormFileCollection files)
        {
            string fileName  = Guid.NewGuid().ToString() + "_img_";
            var    uploads   = Path.Combine(webRootPath, @"images\services");
            var    extension = Path.GetExtension(files[0].FileName);

            using (var fileStreams = new FileStream(Path.Combine(uploads, fileName + extension), FileMode.Create))
            {
                files[0].CopyTo(fileStreams);
            }

            return(@"\images\services\" + fileName + extension);
        }
Beispiel #7
0
        public async Task <IActionResult> CreatePost()
        {
            MenuViewModel.MenuItem.SubCategoryID = Convert.ToInt32(Request.Form["SubCategoryID"].ToString());
            if (!ModelState.IsValid)
            {
                return(View(MenuViewModel));
            }
            dbContext.MenuItems.Add(MenuViewModel.MenuItem);
            await dbContext.SaveChangesAsync();

            //Saving Image Section

            string WebRootPath = hostingEnvironment.WebRootPath;

            Microsoft.AspNetCore.Http.IFormFileCollection files = HttpContext.Request.Form.Files;
            MenuItem menuItemFromDb = await dbContext.MenuItems.FindAsync(MenuViewModel.MenuItem.ID);

            if (files.Count > 0)

            {
                // files has been uploaded
                string uploads   = Path.Combine(WebRootPath, "images");
                string extension = Path.GetExtension(files[0].FileName);
                using (FileStream fileStream = new FileStream(Path.Combine(uploads, MenuViewModel.MenuItem.ID + extension), FileMode.Create))
                {
                    files[0].CopyTo(fileStream);
                }

                menuItemFromDb.Image = @"\images\" + MenuViewModel.MenuItem.ID + extension;
            }
            else
            {
                //no files was uploaded

                var uploads = Path.Combine(WebRootPath, @"\images\" + SD.DefaultFoodImage);
                System.IO.File.Copy(uploads, WebRootPath + @"\images\" + MenuViewModel.MenuItem.ID + ".jpg");
                menuItemFromDb.Image = @"\images\" + MenuViewModel.MenuItem.ID + ".jpg";
            }
            await dbContext.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Beispiel #8
0
 public FormCollection(System.Collections.Generic.Dictionary <string, Microsoft.Extensions.Primitives.StringValues> fields, Microsoft.AspNetCore.Http.IFormFileCollection files = null)
 {
 }
Beispiel #9
0
 public object testUpload(Microsoft.AspNetCore.Http.IFormFileCollection files)
 {
     return(files);
 }
        // Actualiza imagen que este en base de datos
        private static void EditarImagenGuardada(TipoGranContribuyente tipograncontribuyente, string rutaPrincipal, Microsoft.AspNetCore.Http.IFormFileCollection archivos, TipoGranContribuyente tipograncontribuyenteDesdeDb)
        {
            string nombreArchivo  = Guid.NewGuid().ToString();
            var    subidas        = Path.Combine(rutaPrincipal, @"imagenes\tipograncontribuyente");
            var    nuevaExtension = Path.GetExtension(archivos[0].FileName);

            //Aquí subimos nuevamente el archivo
            using (var fileStreams = new FileStream(Path.Combine(subidas, nombreArchivo + nuevaExtension), FileMode.Create))
            {
                archivos[0].CopyTo(fileStreams);
            }
        }
Beispiel #11
0
        public static async Task <bool> UploadFiles(this CloudBlobDirectory directory, Microsoft.AspNetCore.Http.IFormFileCollection files, ILogger <FileStorageService> logger, CancellationToken cancellationToken)
        {
            bool success;

            try
            {
                foreach (var file in files)
                {
                    var blob = directory.GetBlockBlobReference(file.FileName);
                    blob.Properties.ContentType = file.ContentType;

                    await blob.UploadFromStreamAsync(file.OpenReadStream(), cancellationToken);
                }

                success = true;
            }
            catch (Exception ex)
            {
                logger.LogError($"Error uploading files to directory: {directory.Uri} || Message: {ex.Message} || Stack trace: {ex.StackTrace}");
                success = false;
            }

            return(success);
        }
Beispiel #12
0
 public Upload(Microsoft.AspNetCore.Http.IFormFileCollection files, string uploadDir)
 {
     this.files     = files;
     this.uploadDir = uploadDir.Trim('\\');
 }
        public List <Transaction> GetTransactions(Microsoft.AspNetCore.Http.IFormFileCollection files)
        {
            var transactionsList = new List <Transaction>();

            //var transactionRepository = new TransactionRepository();

            if (files.Count > 0)
            {
                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        XmlDocument doc = new XmlDocument();


                        FileStream fileStream = new FileStream(file.FileName, FileMode.Create);
                        file.CopyTo(fileStream);


                        if (fileStream.Position > 0)
                        {
                            fileStream.Position = 0;
                        }

                        doc.Load(fileStream);

                        XmlNodeList elementBankTranList   = doc.GetElementsByTagName("BANKTRANLIST");
                        XmlNodeList elementTrans          = doc.GetElementsByTagName("STMTTRN");
                        string      xmlStringBankTranList = XElement.Parse(elementBankTranList.Item(0).OuterXml).ToString();
                        var         transactions          = new List <Transaction>();

                        XmlRootAttribute xRootTrans = new XmlRootAttribute();
                        xRootTrans.ElementName = "STMTTRN";
                        xRootTrans.IsNullable  = true;
                        XmlSerializer serializadorTrans = new XmlSerializer(typeof(Transaction), xRootTrans);

                        foreach (XmlNode node in elementTrans)
                        {
                            string       xmlStringtTrans   = XElement.Parse(node.OuterXml).ToString();
                            StringReader stringReaderTrans = new StringReader(xmlStringtTrans);
                            var          transaction       = (Transaction)serializadorTrans.Deserialize(stringReaderTrans);
                            bool         exists            = transactionsList.Exists(x => x.dtposted.Equals(transaction.dtposted));
                            stringReaderTrans.Close();
                            if (!exists)
                            {
                                transactions.Add(transaction);
                            }
                        }

                        foreach (var t in transactions)
                        {
                            transactionsList.Add(t);
                        }

                        transactions.Clear();
                        fileStream.Close();
                    }
                }
            }


            return(transactionsList);
        }
 private void GetRestaurantImages(CreateRestaurantViewModel model, List <ImageViewModel> images, Microsoft.AspNetCore.Http.IFormFileCollection files)
 {
     if (files != null && files.Any())
     {
         foreach (var file in files)
         {
             // save file and get the uri
             string uri = SaveImageAndGetUri();
             var    img = new ImageViewModel
             {
                 ImageUrl      = uri,
                 ImagePriority = new Random().Next(1, 10)
             };
             images.Add(img);
         }
         model.Images = images;
     }
 }
        private static void CrearImagenClientes(ClientesVM clientesvm, string rutaPrincipal, Microsoft.AspNetCore.Http.IFormFileCollection archivos)
        {
            string nombreArchivo = Guid.NewGuid().ToString();
            var    subidas       = Path.Combine(rutaPrincipal, @"imagenes\clientes");
            var    extension     = Path.GetExtension(archivos[0].FileName);

            using (var fileStreams = new FileStream(Path.Combine(subidas, nombreArchivo + extension), FileMode.Create))
            {
                archivos[0].CopyTo(fileStreams);
            }
        }
Beispiel #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="files"></param>
        /// <param name="absolutePath"></param>
        /// <param name="relativePath"></param>
        /// <param name="uploadFileMaxSize"></param>
        /// <returns></returns>
        public async static Task <List <string> > Upload(
            //TODO:IE8,9下载后返回一个json,ie8,9的form提交不能识别(真的??),以至于变为下载.除非返回一个"text/html"的content的结果
            Microsoft.AspNetCore.Http.IFormFileCollection files,
            string absolutePath,
            string relativePath,
            int uploadFileMaxSize)
        {
            if (files.Count() == 0)
            {
                throw new Exception("没有上传文件");
            }

            foreach (var file in files)
            {
                if (file.Length > uploadFileMaxSize * 1024 * 1024)
                {
                    throw new Exception($"文件大小不能超出{uploadFileMaxSize}M.");
                }

                var fileName = file.FileName;
                var ext      = Path.GetExtension(fileName).ToLower();

                //string filePath = "";

                //switch (ext.Replace(".", "").ToLower())
                //{
                //    case "jpeg":
                //        filePath = "img";
                //        break;
                //    case "jpg":
                //        filePath = "img";
                //        break;
                //    case "gif":
                //        filePath = "img";
                //        break;
                //    case "png":
                //        filePath = "img";
                //        break;
                //    case "csv":
                //        filePath = "txt";
                //        break;
                //    case "txt":
                //        filePath = "txt";
                //        break;
                //    case "xls":
                //        filePath = "xls";
                //        break;
                //    case "xlsx":
                //        filePath = "xls";
                //        break;
                //    case "doc":
                //        filePath = "doc";
                //        break;
                //    case "docx":
                //        filePath = "doc";
                //        break;
                //}
                //2018-5-22 暂不检查
                //if (filePath == "")
                //{
                //    throw new System.Exception("文件格式不支持.");
                //}
            }

            //测试路径\2018-1-1
            //18-7-4暂时不用加这个日期路径
            //relativePath = Path.Combine(relativePath, DateTime.Now.ToString("yyyyMMdd"));

            //wwwroot的绝对路径\测试路径\2018-1-1
            var path = Path.Combine(absolutePath, relativePath);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var filesNameList = new List <string>();

            foreach (var file in files)
            {
                //var fileName = ContentDispositionHeaderValue
                //.Parse(file.ContentDisposition)
                //.FileName
                //.Trim('"');

                var fileName = file.FileName;
                var ext      = Path.GetExtension(fileName).ToLower();

                var fileSelfName = Path.GetFileNameWithoutExtension(fileName);
                //fileName = fileSelfName + Guid.NewGuid().ToString("N") + ext;

                fileName = $"{fileSelfName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}{ext}";
                var absoluteFilename = Path.Combine(path, $"{fileName}");

                //size += file.Length;
                using (FileStream fs = File.Create(absoluteFilename))
                {
                    await file.CopyToAsync(fs);

                    fs.Flush();
                }

                filesNameList.Add(Path.Combine("/", relativePath, $"{fileName}"));
            }
            return(filesNameList);
        }