Exemplo n.º 1
0
        public ActionResult Upload(string selectedProfileId)
        {
            if (Request != null)
            {
                int profileId = -1;
                if (!string.IsNullOrEmpty(selectedProfileId))
                {
                    profileId = Convert.ToInt32(selectedProfileId);
                }

                HttpPostedFileBase file = Request.Files["fileToBeUploaded"];
                if (file != null)
                {
                    byte[] uploadedFile = new byte[file.InputStream.Length];
                    file.InputStream.Read(uploadedFile, 0, uploadedFile.Length);

                    if (uploadedFile.Length > MaxFileSizeInBytes)
                    {
                        throw new FpmException("Max file upload size is 50 MB");
                    }

                    var fileName = Path.GetFileName(file.FileName);

                    // check is filename unique.
                    var docs = _reader.GetDocuments(fileName);
                    if (docs.Count > 0)
                    {
                        // now check is this name used with current profile.
                        var docFromDatabase = docs.FirstOrDefault(x => x.ProfileId == profileId);
                        if (docFromDatabase != null)
                        {
                            docFromDatabase.ProfileId  = profileId;
                            docFromDatabase.FileName   = fileName;
                            docFromDatabase.FileData   = uploadedFile;
                            docFromDatabase.UploadedBy = new CurrentUser().Name;
                            docFromDatabase.UploadedOn = DateTime.Now;

                            _writer.UpdateDocument(docFromDatabase);
                        }
                    }
                    else
                    {
                        // else overwrite current file for selected profile.
                        var doc = new Document
                        {
                            ProfileId  = profileId,
                            FileName   = fileName,
                            FileData   = uploadedFile,
                            UploadedBy = new CurrentUser().Name,
                            UploadedOn = DateTime.Now
                        };
                        _writer.NewDocument(doc);
                    }
                }
            }

            return(RedirectToAction("Index", new { selectedProfile = selectedProfileId }));
        }