コード例 #1
0
ファイル: FileController.cs プロジェクト: dkest/MicSystem
        public async Task <ResponseResultDto <UploadFileInfo> > UploadOrdinaryFile()
        {
            UploadFileInfo info = new UploadFileInfo();

            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string root = HostingEnvironment.MapPath("/UploadFile/Other/");

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

            var provider = new MultipartFormDataMemoryStreamProvider();

            try
            {
                await Request.Content.ReadAsMultipartAsync(provider);

                var item = provider.Contents[0];
                //foreach (var item in provider.Contents)
                //{
                string fileNameStr   = item.Headers.ContentDisposition.FileName.Trim('"');
                var    arr           = fileNameStr.Split('.');
                string extensionName = arr[arr.Length - 1]; //得到扩展名
                string fileName      = Guid.NewGuid().ToString();
                string fullPath      = Path.Combine(root, fileName + "." + extensionName);
                var    ms            = item.ReadAsStreamAsync().Result;
                using (var br = new BinaryReader(ms))
                {
                    var data = br.ReadBytes((int)ms.Length);
                    File.WriteAllBytes(fullPath, data);
                }
                info = new UploadFileInfo
                {
                    FilePath = "/UploadFile/Other/" + fileName + "." + extensionName
                };
            }
            catch (Exception ex)
            {
                //Logger.FileLoggerHelper.WriteErrorLog(DateTime.Now + ":上传一般文件错误-" + ex.Message);
            }
            return(new ResponseResultDto <UploadFileInfo>
            {
                IsSuccess = true,
                ErrorMessage = string.Empty,
                Result = info
            });
        }
コード例 #2
0
        public async Task <MessageResponse> ProcessHttpRequest(HttpRequestMessage request)
        {
            if (!request.Content.IsMimeMultipartContent())
            {
                return(MessageResponse.info("Invalid media type - multipart"));
            }

            var provider = new MultipartFormDataMemoryStreamProvider();
            await request.Content.ReadAsMultipartAsync(provider);

            var inputFiles = provider.FileData;

            var primaryFilter = "*.*"; //TODO: get from httpRequest
            var primaryFiles  = GetInputFiles(provider, primaryFilter);

            var remitFilter     = "*.*"; //TODO: get from httpRequest
            var remittanceFiles = GetInputFiles(provider, remitFilter);

            var sbStandardFile = _psTool.ProcessMultiDataFile(primaryFiles, remittanceFiles);
            var listErrors     = _psTool.GetErrors();

            if (listErrors.Any())
            {
                return(MessageResponse.error(listErrors));
            }

            //Upload to storage
            var storageConnString = Vault.Current.StorageConnectionString;
            var decryptKey        = Vault.Current.AESKeyBLOB;
            var containerName     = "containerName";  //TODO: where?
            var blobOutputName    = "blobOutputName"; //TODO: how?

            BlobHelper.UploadFile(storageConnString, containerName, blobOutputName, sbStandardFile, decryptKey);

            //Send msg to importWorker
            var messageProperties = new BrokeredMessageProperties();

            messageProperties.Add("siteName", "SiteName");
            var sbConnectionString = Vault.Current.ServiceBusConnectionString;
            var queueName          = "queueName";//TODO:Where?

            MessageHelper.SendMessageToServiceBus(sbConnectionString, queueName, messageProperties);

            return(MessageResponse.ok(null));
        }
コード例 #3
0
        public async Task <HttpResponseMessage> UploadSlot()
        {
            var currentLoggedInUser     = this.CurrentLoggedInUser();
            var currentLoggedInUserRole = this.CurrentLoggedInUserRole(currentLoggedInUser);

            if (!(currentLoggedInUserRole.Name == ConfigurationManager.AppSettings["SUPER_ADMINISTRATOR"] ||
                  currentLoggedInUserRole.Name == ConfigurationManager.AppSettings["USER_ADMINISTRATOR"]))
            {
                return(Request.CreateResponse(HttpStatusCode.Forbidden,
                                              "Lack of sufficient privileges to perform operation."));
            }

            if (!Request.Content.IsMimeMultipartContent())
            {
                return(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType, "Unsupported media type."));
            }
            // Read the file and form data.
            var provider = new MultipartFormDataMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            //// Extract the fields from the form data.
            /**/
            var calendarYear = int.Parse(provider.FormData["calendarYear"].ToString());
            var slotNumber   = int.Parse(provider.FormData["slotNumber"].ToString());
            var slotMessage  = provider.FormData["slotMessage"].ToString();

            var currentCalendar = CurrentCalendar(calendarYear, currentLoggedInUser);

            // Check if files are on the request.
            if (!provider.FileStreams.Any())
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, "No file uploaded."));
            }

            foreach (KeyValuePair <string, Stream> file in provider.FileStreams)
            {
                string fileName = file.Key;
                Stream stream   = file.Value;
                /**/
                string contentType = fileName.Substring(fileName.LastIndexOf('.'));
                //do we have any old values which should be updated?
                InactivatePossibleEarlierSlotWithSameNumber(currentCalendar, slotNumber);
                SaveToDB(stream, contentType, currentCalendar, slotNumber, slotMessage);
            }
コード例 #4
0
        private async Task <DecodingJob> BuildDecodingJob(HttpRequestMessage request)
        {
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var deodingJob = new DecodingJob();

            var provider = new MultipartFormDataMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            var form = provider.FormData;

            deodingJob.Password = form["password"];
            deodingJob.File     = provider.FileStreams.Single().Value;

            return(deodingJob);
        }
コード例 #5
0
        public async Task <IResponseData <IList <FileUploadResponse> > > UploadFile()
        {
            MultipartFormDataMemoryStreamProvider provider = new MultipartFormDataMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            IResponseData <IList <FileUploadResponse> > response = new ResponseData <IList <FileUploadResponse> >();

            try
            {
                IFileService service = IoC.Container.Resolve <IFileService>();
                IList <FileUploadResponse> fileUploadResponse = service.UploadFiles(provider.FileData);
                response.SetData(fileUploadResponse);
            }
            catch (ValidationException ex)
            {
                response.SetErrors(ex.Errors);
                response.SetStatus(System.Net.HttpStatusCode.PreconditionFailed);
            }
            return(response);
        }
コード例 #6
0
        private string ReadFilesFromFormDataAndUploadIfAny(MultipartFormDataMemoryStreamProvider provider)
        {
            string imageFileName = this.defaultImageFileName;

            // Check if files are on the request.
            if (provider.FileStreams.Any())
            {
                foreach (KeyValuePair <string, Stream> file in provider.FileStreams)
                {
                    var fileName = file.Key;
                    var stream   = file.Value;

                    string virtualPath = UploadFile(stream, fileName);

                    if (!String.IsNullOrEmpty(virtualPath))
                    {
                        imageFileName = fileName;
                    }
                }
            }

            return(imageFileName);
        }
コード例 #7
0
        private async Task <EncodingJob> BuildEncodingJob(HttpRequestMessage request)
        {
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var encodingJob = new EncodingJob();

            var provider = new MultipartFormDataMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            var form = provider.FormData;

            encodingJob.FileName             = form["file-name"];
            encodingJob.Password             = form["password"];
            encodingJob.Format               = (ImageFormat)Enum.Parse(typeof(ImageFormat), form["image-format"]);
            encodingJob.EncryptionAlgorithm  = encodingJob.HasPassword ? (EncryptionType)Enum.Parse(typeof(EncryptionType), form["encryption-algorithm"]) : (EncryptionType?)null;
            encodingJob.CompressionAlgorithm = ParseNullableEnum <CompressionType>(form["compression-algorithm"]);
            encodingJob.CompressionLevel     = (CompressionLevel)Enum.Parse(typeof(CompressionLevel), form["compression-level"]);

            var directoryInput = form.GetValues("directories[]") ?? new string [0];

            if (directoryInput == null)
            {
                return(null);
            }

            Dictionary <string, List <File> > directories = directoryInput.ToDictionary(directory => directory, directory => new List <File>());

            KeyValuePair <string, Stream> embeddedImageUpload = provider.FileStreams.FirstOrDefault(file => file.Key == "embedded-image");

            if (embeddedImageUpload.Key != null)
            {
                int maxFileSize = TranscodingConfiguration.EmbeddedPictureLimits.Bytes;
                if (embeddedImageUpload.Value.Length > maxFileSize)
                {
                    throw new BadRequestException("The selected cover picture exceeds the maximum file size of " + FileSize.Format(maxFileSize));
                }

                var pixelStorage = (EmbeddedImage.PixelStorage)Enum.Parse(typeof(EmbeddedImage.PixelStorage), form["pixel-storage-level"]);
                encodingJob.EmbeddedImage = new EmbeddedImage(Image.FromStream(embeddedImageUpload.Value), pixelStorage);

                var maxHeight = TranscodingConfiguration.EmbeddedPictureLimits.Height;
                var maxWidth  = TranscodingConfiguration.EmbeddedPictureLimits.Width;
                if (encodingJob.EmbeddedImage.Image.Height > maxHeight || encodingJob.EmbeddedImage.Image.Width > maxWidth)
                {
                    throw new BadRequestException("The selected cover picture exceeds the maximum size of " + maxWidth + " x " + maxHeight + "px");
                }
            }

            foreach (var file in provider.FileStreams)
            {
                if (file.Key == "embedded-image")
                {
                    continue;
                }
                var key       = file.Key;
                var name      = form[key + ".name"];
                var directory = form[key + ".directory"];
                if (!directories.ContainsKey(directory))
                {
                    directories.Add(directory, new List <File>());
                }

                directories[directory].Add(new File(name, file.Value));
            }

            foreach (var directory in directories)
            {
                encodingJob.Directories.Add(new Directory(directory.Key, directory.Value));
            }

            long encodedFilesLength = encodingJob.Directories
                                      .SelectMany(directory => directory.Files)
                                      .Sum(file => file.Length);

            var maxEncodedDataSize =
                GetMaxDataSizeFor(encodingJob.EmbeddedImage == null
                    ? (EmbeddedImage.PixelStorage?)null
                                  : encodingJob.EmbeddedImage.EmbeddedPixelStorage);

            if (encodedFilesLength > maxEncodedDataSize)
            {
                throw new BadRequestException("The selected files exceeds the maximum data size of " + FileSize.Format(maxEncodedDataSize) + " for the specified configuration");
            }

            return(encodingJob);
        }
コード例 #8
0
        public async Task <HttpResponseMessage> PutProduct(string id)
        {
            if (Request.Content.IsMimeMultipartContent("form-data"))
            {
                if (Request.Content.IsMimeMultipartContent())
                {
                    // Read the file and form data.
                    var provider = new MultipartFormDataMemoryStreamProvider();
                    await Request.Content.ReadAsMultipartAsync(provider);

                    string imageFileName = ReadFilesFromFormDataAndUploadIfAny(provider);

                    // Extract the other fields from the form data.
                    string name             = provider.FormData["name"];
                    string description      = provider.FormData["description"];
                    string categoryIdString = provider.FormData["categoryId"];

                    if (!String.IsNullOrEmpty(name) &&
                        !String.IsNullOrEmpty(categoryIdString))
                    {
                        // TODO: additional exception handling
                        int idParsed   = Convert.ToInt32(id);
                        int categoryId = Convert.ToInt32(categoryIdString);

                        Product editedProduct = db.Products.Where(p => p.Id == idParsed).FirstOrDefault();

                        if (editedProduct != null)
                        {
                            editedProduct.Name        = name;
                            editedProduct.Description = description;
                            editedProduct.CategoryId  = categoryId;

                            string currentImage = editedProduct.Image;

                            // if there is a new image selected, delete the old image from file system
                            // if it is not the default image
                            if (currentImage != this.defaultImageFileName && imageFileName != this.defaultImageFileName)
                            {
                                DeleteImageFromFileSystem(currentImage);
                            }

                            // if a new image is uploaded for the product
                            // set the product image to it
                            if (imageFileName != this.defaultImageFileName)
                            {
                                editedProduct.Image = imageFileName;
                            }

                            //db.Products.Add(product);
                            db.Entry(editedProduct).State = EntityState.Modified;
                            db.SaveChanges();
                        }
                        else
                        {
                            return(Request.CreateResponse(HttpStatusCode.BadRequest, "Error: The product cannot be found"));
                        }
                    }
                    else
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest, "Error: The following fields are required: Name, Category"));
                    }
                }
            }

            return(Request.CreateResponse(HttpStatusCode.OK, "Product has been successfully edited"));
        }
コード例 #9
0
        public async Task <HttpResponseMessage> UploadFile(string folderScoId)
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var provider = new MultipartFormDataMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            string name        = provider.FormData["name"];
            string description = provider.FormData["description"];
            string customUrl   = provider.FormData["customUrl"];

            if (!provider.FileStreams.Any())
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);

                //return Content(HttpStatusCode.BadRequest, "No file uploaded");
            }
            if (provider.FileStreams.Count != 1)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
                //return Content(HttpStatusCode.BadRequest, "Single file expected");
            }

            try
            {
                string fileName = provider.FileStreams.First().Key;
                MultipartFormDataMemoryStreamProvider.FileContent stream = provider.FileStreams.First().Value;

                var           ac             = this.GetUserProvider();
                var           contentService = new ContentService(Logger, ac);
                var           helper         = new ContentEditControllerHelper(Logger, ac);
                int           fileSize;
                ScoInfoResult createdFile = helper.UploadFile(folderScoId, name, description, customUrl, fileName, stream.ContentType, stream.Stream, out fileSize);

                var sco = ac.GetScoContent(createdFile.ScoInfo.ScoId);
                var dto = new ScoContentDtoMapper().Map(sco.ScoContent);
                //TRICK:
                dto.ByteCount = fileSize;

                string output   = JsonSerializer.JsonSerialize(dto.ToSuccessResult());
                var    response = new HttpResponseMessage();
                response.Content = new StringContent(output);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                return(response);
            }
            catch (Exception ex)
            {
                IUserMessageException userError = ex as IUserMessageException;
                if (userError != null)
                {
                    string output = JsonSerializer.JsonSerialize(OperationResultWithData <ScoContentDto> .Error(ex.Message));
                    //JsonConvert.SerializeObject(OperationResultWithData<ScoContentDto>.Error(ex.Message));
                    var response = new HttpResponseMessage();
                    response.Content = new StringContent(output);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                    return(response);
                }

                throw;
            }
        }
コード例 #10
0
        public async Task <HttpResponseMessage> Upload()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                return(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType, "Unsupported media type."));
            }
            // Read the file and form data.
            MultipartFormDataMemoryStreamProvider provider = new MultipartFormDataMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            // Extract the fields from the form data.
            string description = provider.FormData["ProjectId"];


            foreach (HttpContent obj in provider.Contents)
            {
                Console.WriteLine(obj);
                if (obj.ToString() == "TaskId")
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, obj));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "BAAAAD REq"));
                }
            }



            int uploadType;

            //   if (!Int32.TryParse(provider.FormData["uploadType"], out uploadType))
            //   {
            //      return Request.CreateResponse(HttpStatusCode.BadRequest, "Upload Type is invalid.");
            // }


            if (description != null)
            {
                Console.WriteLine(description);
            }

            // Check if files are on the request.
            if (!provider.FileStreams.Any())
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, "No file uploaded."));
            }

            foreach (KeyValuePair <string, Stream> file in provider.FileStreams)
            {
                string fileName    = file.Key;
                string contentType = file.Key;
                Stream stream      = file.Value;


                using (Stream fs = stream)
                {
                    using (BinaryReader br = new BinaryReader(fs))
                    {
                        byte[] bytes = br.ReadBytes((Int32)fs.Length);
                        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
                        {
                            string query = "insert into Files values (@Name, @ContentType, @Data)";
                            using (SqlCommand cmd = new SqlCommand(query, con))
                            {
                                cmd.Parameters.AddWithValue("@Name", fileName);
                                cmd.Parameters.AddWithValue("@ContentType", contentType);
                                cmd.Parameters.AddWithValue("@Data", bytes);
                                con.Open();
                                cmd.ExecuteNonQuery();
                                con.Close();
                            }
                        }
                    }
                }
            }

            return(Request.CreateResponse(HttpStatusCode.OK, "Successfully Uploaded: "));
        }
コード例 #11
0
        public async Task <List <Dictionary <string, string> > > ImgUpload()
        {
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            List <Dictionary <string, string> > list = new List <Dictionary <string, string> >();
            string pata = "/File/uploadpic/" + DateTime.Now.ToString("yyyyMMdd");

            LogHelper.WriteLog("pata : " + pata, "UTIController.FileUpload");
            string root = HttpContext.Current.Server.MapPath(pata + "/original");//指定要将文件存入的服务器物理位置

            LogHelper.WriteLog("root: " + root, "UTIController.FileUpload");
            if (!Directory.Exists(root))//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(root);
            }
            var provider = new MultipartFormDataMemoryStreamProvider();

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                LogHelper.WriteLog("Read the form data", "UTIController.FileUpload");
                // This illustrates how to get the file names.
                foreach (var fileContent in provider.FileContents)
                {
                    LogHelper.WriteLog("This illustrates how to get the file names.", "UTIController.FileUpload");
                    Dictionary <string, string> dic = new Dictionary <string, string>();
                    string fileName = fileContent.Headers.ContentDisposition.FileName.Replace("\"", "");
                    dic.Add("OldFileName", fileName);
                    string Ext = Path.GetExtension(fileName).ToLowerInvariant();
                    if (Ext == ".png" || Ext == ".jpg" || Ext == ".jpeg")
                    {
                        dic.Add("ExtName", Ext);
                        fileName = EncyryptionUtil.GetMd5Utf8(EncyryptionUtil.AESEncrypt(Guid.NewGuid().ToString())) + Ext;
                        dic.Add("NewFileName", fileName);
                        dic.Add("FilePath", FlieServiceUrl + pata + "/original/" + fileName);
                        var stream = await fileContent.ReadAsStreamAsync();

                        using (StreamWriter sw = new StreamWriter(Path.Combine(root, fileName)))
                        {
                            dic.Add("status", "1");
                            stream.CopyTo(sw.BaseStream);
                            sw.Flush();
                        }
                        PicHelper.PicZoomAuto(HttpContext.Current.Server.MapPath(pata + "/original/" + fileName), HttpContext.Current.Server.MapPath(pata), fileName);
                    }
                    else
                    {
                        dic.Add("status", "0");
                        dic.Add("errmsg", "格式不正确");
                    }
                    list.Add(dic);
                }
                //TODO:这样做直接就将文件存到了指定目录下,暂时不知道如何实现只接收文件数据流但并不保存至服务器的目录下,由开发自行指定如何存储,比如通过服务存到图片服务器
                //foreach (var key in provider.FormData.AllKeys)
                //{//接收FormData
                //    dic.Add(key, provider.FormData[key]);
                //}
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(e.Message);
                throw;
            }
            return(list);
        }