示例#1
0
        public void CanMap_UploadFileData_to_StorageFileSaveModel()
        {
            var mapper = GetMapper();

            var src = new UploadFileData(userId: 11, adId: 1, name: "name", fileType: FileType.Jpeg, bytes: new byte[] { });
            var dst = mapper.Map <StorageFileSaveModel>(src);
        }
示例#2
0
 private void ProcessUploadData(long clientID, UploadFileData data, ArraySegment <byte> payload)
 {
     if (_sessionDict.TryGetValue(data.UploadSessionID, out UploadFileSession uploadSession))
     {
         uploadSession.SaveFileData(payload);
     }
 }
        public Result <MediaModel> UploadPicture(UploadFileData imageData)
        {
            if (imageData == null)
            {
                return(Result <MediaModel> .NewFailure($"Parameter '{nameof(imageData)}' is NULL."));
            }


            try
            {
                var savedFile = new SavedFileInfo();
                foreach (var option in ResizeOptions)
                {
                    var rScaledImage = _imgConvUtil.GetScaledJpegBytes(imageData.Bytes, option);
                    if (!rScaledImage.Success)
                    {
                        return(Result <MediaModel> .NewFailure(rScaledImage.ErrorMessage));
                    }

                    var scaledImage = rScaledImage.Value;

                    var storageSaveFileModel = _mapper.Map <StorageFileSaveModel>(imageData);
                    storageSaveFileModel.Bytes = scaledImage.Bytes;
                    var rStorageFileData = _filesBinaryStorage.SaveFile(storageSaveFileModel: storageSaveFileModel);
                    if (!rStorageFileData.Success)
                    {
                        return(Result <MediaModel> .NewFailure(rStorageFileData.ErrorMessage));
                    }

                    var imgType       = _mapper.Map <ImageType>(option.OperationType);
                    var scaledPicInfo = new SavedScaledPicInfo(
                        dimention: scaledImage.Size,
                        filePathParts: rStorageFileData.Value.RelativeFilePathParts,
                        imgType: imgType);
                    savedFile.AddScaledPicInfo(data: scaledPicInfo);
                }

                // Save the pic data to table.
                var storageSaveMediaModel = GetStorageSaveMediaModel(imageData, savedFile);
                var resultStorageSaveFile = _filesInfoStorage.SaveMedia(storageSaveMediaModel);
                if (!resultStorageSaveFile.Success)
                {
                    return(Result <MediaModel> .NewFailure(resultStorageSaveFile.ErrorMessage));
                }

                var result = _mapper.Map <MediaModel>(resultStorageSaveFile.Value);

                return(Result <MediaModel> .NewSuccess(result));
            }
            catch (Exception ex)
            {
                return(Result <MediaModel> .NewFailure(ex.ToString()));
            }
        }
        public Result <UploadFileData> GetFileData(long userId, long?adId, IFormFile file)
        {
            if (file == null)
            {
                return(Result <UploadFileData> .NewFailure($"Passed parameter {nameof(file)} is NULL."));
            }

            var fileLengthString = file.Length.ToString();

            if (!int.TryParse(fileLengthString, out var length))
            {
                return(Result <UploadFileData> .NewFailure($"File is too long. File length: '{fileLengthString}' bytes."));
            }

            if (length > UploadFileMaxLengthBytes)
            {
                return(Result <UploadFileData> .NewFailure($"File length: '{length}' is more than allowed: '{UploadFileMaxLengthBytes}'."));
            }


            var fileTypes = new byte[length];

            using (var ms = new MemoryStream())
            {
                file.CopyTo(ms);
                ms.Position = 0;
                ms.Read(fileTypes, 0, length);
            }

            var fileType = GetFileType(file.ContentType);

            var fileData = new UploadFileData(
                userId: userId,
                adId: adId,
                name: file.FileName,
                fileType: fileType,
                bytes: fileTypes);

            return(Result <UploadFileData> .NewSuccess(fileData));
        }
        private StorageMediaCreateModel GetStorageSaveMediaModel(UploadFileData imageData, SavedFileInfo savedFile)
        {
            var storageSaveMediaModel = new StorageMediaCreateModel()
            {
                AdId             = imageData.AdId,
                FileType         = StorageFileType.Jpeg,
                IsPrimary        = imageData.IsPrimary,
                DateCreated      = DateTime.UtcNow,
                OriginalFileName = imageData.Name,
                Position         = imageData.Position
            };

            foreach (var picData in savedFile.ScaledPicsInfo)
            {
                storageSaveMediaModel.ScaledPicData.Add(new StoragePicScaledData()
                {
                    Size      = picData.Dimention,
                    PathParts = picData.FilePathParts,
                    PicType   = _mapper.Map <StoragePicType>(picData.ImgType)
                });
            }

            return(storageSaveMediaModel);
        }
        private void UploadProc(object obj)
        {
            TcpModelClient uploadClient = new TcpModelClient(false, (int)MessageHeader.Model, JsonModelMessageConvert.Default);

            try
            {
                uploadClient.Connect(ServerIPAddress, ServerPort);
                SetProgress(0, 0);
                string filePath = (string)obj;
                //1.upload file request
                AddLog("Request to upload file...");
                FileInfo fi = new FileInfo(filePath);
                UploadFileBeginRequest uploadRequestMsg = new UploadFileBeginRequest()
                {
                    FileName = Path.GetFileName(filePath),
                    FileSize = fi.Length
                };
                UploadFileBeginResponse uploadReponseMsg = uploadClient.QueryAsync <UploadFileBeginResponse>(uploadRequestMsg).Result;

                if (!uploadReponseMsg.AllowUpload)
                {
                    throw new Exception("upload failed:" + uploadReponseMsg.Message);
                }
                AddLog("can upload file");
                //2.upload file data
                UploadFileData uploadData = new UploadFileData()
                {
                    UploadSessionID = uploadReponseMsg.UploadSessionID
                };
                FileStream fs        = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                byte[]     buffer    = new byte[10 * 1024];
                long       totalSend = 0;
                int        lastTick  = Environment.TickCount;
                int        startTick = Environment.TickCount;
                while (true)
                {
                    //process cancellation
                    if (_cancelTokenSource.IsCancellationRequested)
                    {
                        fs.Close();
                        UploadFileCancelRequest cancelRequest = new UploadFileCancelRequest()
                        {
                            UploadSessionID = uploadReponseMsg.UploadSessionID
                        };
                        UploadFileCancelResponse cancelResponse = uploadClient.QueryAsync <UploadFileCancelResponse>(cancelRequest, int.MaxValue).Result;
                        AddLog("the uploading is cancelled");
                        return;
                    }
                    int readLen = fs.Read(buffer, 0, buffer.Length);
                    if (readLen <= 0)
                    {
                        double percent = (double)totalSend * 100.0 / (double)fi.Length;
                        double speed   = (double)totalSend * 1000.0 / ((double)(Environment.TickCount - startTick) * 1024.0 * 1024.0);
                        SetProgress(percent, speed);
                        fs.Close();
                        break;
                    }
                    totalSend += readLen;
                    int curTick = Environment.TickCount;
                    if (curTick - lastTick >= 300)
                    {
                        double percent = (double)totalSend * 100.0 / (double)fi.Length;
                        double speed   = (double)totalSend * 1000.0 / ((double)(curTick - startTick) * 1024.0 * 1024.0);
                        SetProgress(percent, speed);
                        lastTick = Environment.TickCount;
                    }
                    GeneralMessage generalMessage = _tcpClient.ConvertToGeneralMessage(uploadData);
                    generalMessage.Payload = new ArraySegment <byte>(buffer, 0, readLen);
                    uploadClient.SendMessage(generalMessage.Serialize());
                }

                //3.finish upload
                UploadFileEndRequest endRequest = new UploadFileEndRequest
                {
                    ID              = Guid.NewGuid(),
                    LastWriteTime   = fi.LastWriteTime,
                    UploadSessionID = uploadReponseMsg.UploadSessionID
                };
                UploadFileEndResponse endResponse = uploadClient.QueryAsync <UploadFileEndResponse>(endRequest, int.MaxValue).Result;
                if (endResponse.Success)
                {
                    SetProgress(100, -1);
                    AddLog("upload finished");
                }
                else
                {
                    AddLog("upload failed:" + endResponse.Message);
                }
            }
            finally
            {
                uploadClient.Close();
            }
        }
示例#7
0
 public Task <FileInfoDto> UploadFiles([FromForm] UploadFileData data)
 {
     return(_webFilesService.Save(data));
 }
示例#8
0
        public void uploadFile(Form attachedForm, FileType type, string fullFileName, string fileName, 
            byte[] fileContent, byte[] parseData, Dictionary<string,string> paramKeyValues)
        {
            new Thread(delegate()
            {
                byte[] respData;
                string json;
                WebHeaderCollection headers;
                string url = getUrl(Action.uploadfile);
                url += "/" + type.ToString();
                if (paramKeyValues != null && paramKeyValues.Count > 0)
                {
                    int i = 0;
                    foreach (KeyValuePair<string,string> pair in paramKeyValues)
                    {
                        if (i == 0)
                            url += "?";
                        else
                            url += "&";
                        url += pair.Key + "=" + pair.Value;
                        i++;
                    }
                }

                UploadFileData uploadFileData = new UploadFileData();
                uploadFileData.ShortName = fileName;
                uploadFileData.Uploader = HTTPAgent.Username;
                uploadFileData.Md5 = Utility.MD5File(fullFileName);
                uploadFileData.FileContent = fileContent;
                uploadFileData.ParseData = parseData;
                byte[] sendBytes = uploadFileData.ToBytes();

                HttpStatusCode statusCode = HTTPRequest.MakeRequest(url, "POST",
                    Constants.JSON_MIME, Constants.RAW_MIME,
                    sendBytes, out respData, out headers);
                if (statusCode == HttpStatusCode.Accepted)
                {
                    FileDescription description;
                    if (respData != null)
                    {
                        json = Encoding.UTF8.GetString(respData);
                        description = Utility.JsonDeserialize<FileDescription>(json);
                        if (onUploadFileSuccessfully != null)
                        {
                            attachedForm.BeginInvoke(onUploadFileSuccessfully, type, description, parseData);
                        }
                    }
                }
                else
                {
                    ErrorMessage errMsg = null;
                    if (respData != null)
                    {
                        json = Encoding.UTF8.GetString(respData);
                        errMsg = Utility.JsonDeserialize<ErrorMessage>(json);
                    }

                    if (onUploadFileFailed != null)
                        attachedForm.BeginInvoke(onUploadFileFailed, fullFileName, statusCode, errMsg);
                }

            }).Start();
        }