示例#1
0
        public IHttpActionResult PutFileUpload(int id, FileUpload fileUpload)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != fileUpload.imageid)
            {
                return(BadRequest());
            }

            db.Entry(fileUpload).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!FileUploadExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
示例#2
0
        public ActionResult Create([Bind(Include = "FileID,FilePath")] File file)
        {
            if (ModelState.IsValid)
            {
                db.Files.Add(file);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(file));
        }
        //Download Action
        public async Task <IActionResult> Download(string filename)
        {
            if (filename == null)
            {
                return(Content("filename not present"));
            }

            var path = Path.Combine(Directory.GetCurrentDirectory(), Services.Constants.StoragePath, filename);

            var memory = new MemoryStream();

            using (var stream = new FileStream(path, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }

            //update download counter
            using (var ctx = new FileUploadContext())
            {
                ctx.Files.FirstOrDefault(f => f.FileName == filename).Downloads++;

                ctx.SaveChanges();
            }
            Startup.fileUploadModels.FirstOrDefault(f => f.FileName == filename).Downloads++;

            memory.Position = 0;
            return(File(memory, MimeTypesMap.GetMimeType(filename), Path.GetFileName(path)));
        }
        public ActionResult UploadFiles([FromForm] FileUploadModel fileUploadModel)
        {
            try
            {
                using (FileUploadContext dbContext = new FileUploadContext())
                {
                    var engModel = new EngagementUploadFile()
                    {
                        FileName     = fileUploadModel.FileName,
                        UploadedBy   = fileUploadModel.UploadedBy,
                        UploadedDate = DateTime.Now
                    };

                    using (var memoryStream = new MemoryStream())
                    {
                        fileUploadModel.File.CopyTo(memoryStream);
                        engModel.UploadedFile    = memoryStream.ToArray();
                        engModel.FileContentType = fileUploadModel.File.ContentType;
                    }

                    dbContext.EngagementUploadFile.Add(engModel);
                    dbContext.SaveChanges();
                }
            }
            catch (Exception ex)
            {
            }
            return(Ok());
        }
示例#5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Expires = -1;
            try
            {
                HttpPostedFile file = Request.Files["uploaded"];

                ZipFile       zipFile    = ZipFile.Read(file.InputStream);
                StringBuilder zipContent = new StringBuilder();
                foreach (var zipEntry in zipFile.Entries)
                {
                    MemoryStream memoryStream = new MemoryStream();
                    zipEntry.Extract(memoryStream);

                    memoryStream.Position = 0;
                    StreamReader reader = new StreamReader(memoryStream);
                    zipContent.AppendLine(reader.ReadToEnd());
                }

                FileUploadContext db = new FileUploadContext();
                db.Files.Add(new Models.File()
                {
                    Content = zipContent.ToString()
                });
                db.SaveChanges();


                Response.ContentType = "application/json";
                Response.Write("{}");
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
 public ActionResult Create(Student student, HttpPostedFileBase doc)
 {
     if (ModelState.IsValid && doc != null)
     {
         var filename  = Path.GetFileName(doc.FileName);
         var extension = Path.GetExtension(filename).ToLower();
         if (extension == ".jpg" || extension == ".png")
         {
             var path = HostingEnvironment.MapPath(Path.Combine("~/Content/Images/", filename));
             doc.SaveAs(path);
             student.ImageUrl = "~/Content/Images/" + filename;
             db.Students.Add(student);
             db.SaveChanges();
             return(RedirectToAction("Index"));
         }
         else
         {
             ModelState.AddModelError("", "Document size must be less then 5MB");
             return(View(student));
         }
     }
     ModelState.AddModelError("", "Photo is required");
     return(View(student));
 }
示例#7
0
        public void DeleteFile(string filename)
        {
            if (filename != null)
            {
                var path = Path.Combine(Directory.GetCurrentDirectory(), Constants.StoragePath, filename);

                File.Delete(path);
                Startup.fileUploadModels.RemoveAll(f => f.FileName == filename);

                using (var ctx = new FileUploadContext())
                {
                    FileUploadModel file = ctx.Files.Where(f => f.FileName == filename).FirstOrDefault();

                    ctx.Files.Remove(file);
                    ctx.SaveChanges();
                }
            }
        }
示例#8
0
        public void UploadFiles(List <IFormFile> files, string name)
        {
            long size = files.Sum(f => f.Length);

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    // full path to file
                    var filePath = Path.Join(Constants.StoragePath, formFile.FileName);
                    //Save File Info
                    FileUploadModel fileUploadModel = new FileUploadModel()
                    {
                        Id         = Guid.NewGuid(),
                        Author     = name,
                        FileName   = formFile.FileName,
                        Created_At = DateTime.Now,
                        Downloads  = 0
                    };

                    if (!Startup.fileUploadModels.Any(f => f.FileName == fileUploadModel.FileName))
                    {
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            formFile.CopyTo(stream);
                        }

                        using (var ctx = new FileUploadContext())
                        {
                            ctx.Files.Add(fileUploadModel);
                            ctx.SaveChanges();
                        }

                        Startup.fileUploadModels.Add(fileUploadModel);
                    }
                }
            }
        }
        public void analyze(string filepath)
        {
            ViewData["title"] = "Result";

            FileStream   fs = new FileStream(filepath, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            Byte         content;
            char         c;
            long         totallen = br.BaseStream.Length;//total length

            int border       = 0;
            int flag         = 0;
            int paragraph_sz = 16; //unit:byte
            int section_c    = 7;  //一共有多少个section,最多有7个

            string[] section_name = new string[7];
            int[]    section_sz   = new int[7];
            int[]    total_sz     = new int[7];//.text .rsrc .reloc

            while (br.BaseStream.Position < br.BaseStream.Length)
            {
                switch (flag)
                {
                case 0:    //MZ header
                    ViewBag.MZid = br.ReadBytes(2);

                    br.ReadBytes(6);

                    ViewBag.MZsize = Reverseread(br.ReadBytes(2), 0, 1);    //get the length of the MZ header
                    int len = Calculate(ViewBag.MZsize, 0, 1);

                    br.ReadBytes(len * paragraph_sz - 10);

                    flag++;
                    break;

                case 1:    //default part --- 64 bytes
                    br.ReadBytes(14);

                    string info = string.Empty;
                    for (int i = 0; i < 39; i++)
                    {
                        content = br.ReadByte();
                        c       = (char)content;
                        info    = info + c;
                        //为啥不能用append呢……QAQ
                    }    //This program cannot be run in DOS mode.
                    ViewBag.info = info;
                    br.ReadBytes(11);

                    flag++;
                    break;

                case 2:    //PE Header

                    ViewBag.PEid = br.ReadBytes(4);

                    ViewBag.MachineType = Reverseread(br.ReadBytes(2), 0, 1);

                    ViewBag.sectionamount = Reverseread(br.ReadBytes(2), 0, 1);    //get the length of the MZ header
                    section_c             = Calculate(ViewBag.sectionamount, 0, 1);

                    br.ReadBytes(240);

                    /*Clear the dbcontext, sectioncount is 7 in maximum*/
                    int sectioncount = _context.Section.Count();
                    for (int i = 0; i < sectioncount; i++)
                    {
                        var Dsection = _context.Section.First();
                        _context.Section.Remove(Dsection);
                        _context.SaveChanges();
                    }


                    flag++;
                    break;

                case 3:    //section header information
                    info = string.Empty;
                    for (int i = 0; i < 8; i++)
                    {
                        content = br.ReadByte();
                        if (content != 0)
                        {
                            c    = (char)content;
                            info = info + c;
                        }
                    }
                    section_name[border] = info;
                    var newsection = new Section
                    {
                        Name     = info,
                        Size     = Reverseread(br.ReadBytes(4), 0, 3),
                        Vaddr    = Reverseread(br.ReadBytes(4), 0, 3),
                        Total_sz = Reverseread(br.ReadBytes(4), 0, 3)
                    };

                    section_sz[border] = Calculate(newsection.Size, 0, 3);
                    total_sz[border]   = Calculate(newsection.Total_sz, 0, 3);

                    br.ReadBytes(20);

                    _context.Section.Add(newsection);
                    _context.SaveChanges();

                    border++;
                    if (border >= section_c)    //section header 结束
                    {
                        flag++;
                        br.ReadBytes(16);    //Reserved
                    }

                    break;

                case 4:    //Section Content
                    for (int i = 0; i < section_c; i++)
                    {
                        var    Thesection = _context.Section.First(a => a.Name == section_name[i]);
                        byte[] Thecontent = br.ReadBytes(section_sz[i]);
                        Thesection.content = Thecontent;
                        _context.SaveChanges();
                        br.ReadBytes(total_sz[i] - section_sz[i]);
                    }
                    flag++;
                    break;

                default:
                    br.ReadByte();
                    break;
                }
            }

            br.Close();
            fs.Close();
        }
 private void UploadFileToDb(FileUploadModel fileUpload)
 {
     db.fileUploadModel.Add(fileUpload);
     db.SaveChanges();
 }
示例#11
0
        public async Task <IActionResult> Upload([FromForm] IFormFile uploadFile)
        {
            var nowStamp = DateTime.Now;
            var rootPath = _env.ContentRootPath;

            if (uploadFile == null)
            {
                return(NoContent());
            }

            // 根据现有信息创建文件实体
            var file = new File {
                FileName = uploadFile.FileName, Type = uploadFile.ContentType, UploadDate = nowStamp
            };

            if (uploadFile.Length > 0)
            {
                using (var stream = new System.IO.MemoryStream())
                {
                    // 读取上传文件计算 MD5
                    await uploadFile.CopyToAsync(stream);

                    stream.Position = 0;
                    var md5Arr = MD5.Create().ComputeHash(stream);

                    StringBuilder sBuilder = new StringBuilder();

                    for (int i = 0; i < md5Arr.Length; i++)
                    {
                        // x2 代表转为 16 进制长度为 2 的 string
                        sBuilder.Append(md5Arr[i].ToString("x2"));
                    }

                    file.MD5 = sBuilder.ToString();

                    // 将文件内容转为字节数组并写入实体
                    file.FileContent = stream.ToArray();

                    var extension = "";

                    // 处理特定的文档预览
                    switch (file.Type)
                    {
                    case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                        extension = ".docx";
                        break;

                    case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                        extension = ".xlsx";
                        break;

                    case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
                        extension = ".pptx";
                        break;

                    case "application/msword":
                        extension = ".doc";
                        break;

                    case "application/vnd.ms-excel":
                        extension = ".xls";
                        break;

                    case "application/vnd.ms-powerpoint":
                        extension = ".ppt";
                        break;

                    case "application/pdf":
                        extension = ".pdf";
                        break;
                    }

                    if (extension != "")
                    {
                        // 进行预览图片的生成并写入到实体中
                        var resultImage = CovertFile.Covert(rootPath, file.MD5, extension, stream);

                        if (System.IO.File.Exists(resultImage))
                        {
                            using (var previewStream = new System.IO.FileStream(resultImage, System.IO.FileMode.Open))
                            {
                                await stream.FlushAsync();

                                stream.Position = 0;
                                await previewStream.CopyToAsync(stream);

                                file.PreviewImage = stream.ToArray();
                            }

                            // 删除临时生成的图片
                            System.IO.File.Delete(resultImage);
                        }
                    }
                }

                // 将生成的实体添加到 Model 中并与数据库同步
                await _context.File.AddAsync(file);

                _context.SaveChanges();

                return(Ok(new FileReturnInfo(file)));
            }
            else
            {
                return(NoContent());
            }
        }