Пример #1
0
        /// <summary>
        /// Uploads a file to the web service.
        /// File type needs to be specified for the file.
        /// File content is compressed by GZIP.
        /// In case of an error an exception is thrown.
        /// </summary>
        /// <returns>JToken. Properties: FileReference, TargetId, ParentFileReference, FileType, FileTimestamp, Status</returns>
        public static JToken UploadFile(UploadFileInput input, CancellationToken cancellationToken)
        {
            string customerId  = input.CustomerId;
            string environment = input.Environment;
            string fileInput   = input.FileInput;
            string fileType    = input.FileType;
            string url         = input.Url;

            var stringParameters = new[]
            {
                new KeyValuePair <string, string>("customerId", customerId),
                new KeyValuePair <string, string>("fileInput", fileInput),
                new KeyValuePair <string, string>("fileType", fileType)
            };

            X509Certificate2 cert = CertificateService.FindCertificate(input.CertificateIssuedBy);

            Validators.ValidateParameters(input.Url, cert, environment, stringParameters);

            var env = (Environment)Enum.Parse(typeof(Environment), environment);

            var encoding = string.IsNullOrEmpty(input.FileEncoding) ? Encoding.UTF8 : Encoding.GetEncoding(input.FileEncoding);

            var    message             = MessageService.GetUploadFileMessage(cert, customerId, env, input.RequestId, fileInput, fileType, encoding);
            var    result              = WebService.CallWebService(url, message, MessageService.SoftwareId, input.ConnectionTimeOutSeconds, cancellationToken);
            string resultXml           = result.Result.Body;
            var    applicationResponse = CheckResultForErrorsAndReturnApplicationResult(resultXml);

            return(Helper.GetFileInfoFromResponseXml(applicationResponse));
        }
 public Task <ReadOnlyMemory <byte> > PromptToUploadFile()
 {
     _input = new UploadFileInput();
     _taskCompletionSource = new TaskCompletionSource <ReadOnlyMemory <byte> >();
     StateHasChanged();
     return(_taskCompletionSource.Task);
 }
Пример #3
0
        public Rtn <Enclosure> uploadFile([FromForm] UploadFileInput input)
        {
            var    strArr   = input.filename.Split(".");
            var    ext      = strArr.Length > 0 ? strArr[strArr.Length - 1] : "";
            Stream fromFile = input.file.OpenReadStream();

            var res  = OSSService.uploadFile(fromFile, input.filename);
            var url  = "https://cucr.oss-cn-beijing.aliyuncs.com/" + ((int)DateTime.Now.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds) + "/" + input.filename;
            var file = new Enclosure {
                fjName = input.filename, fjAddress = url, fjType = ext, fileSize = fromFile.Length
            };

            this.oaContext.enclosures.Add(file);
            this.oaContext.SaveChanges();
            return(Rtn <Enclosure> .Success(file));
        }
Пример #4
0
        public async Task <dynamic> UploadObject([FromForm] UploadFileInput input)
        {
            // basic input validation
            if (string.IsNullOrWhiteSpace(input.bucketKey))
            {
                throw new System.Exception("BucketKey parameter was not provided.");
            }

            if (input.inputFile == null)
            {
                throw new System.Exception("Missing file to upload"); // for now, let's support just 1 file at a time
            }
            string bucketKey = input.bucketKey;

            var fileSavePath = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot\\appdata", Path.GetFileName(input.inputFile.FileName));

            using (var stream = new FileStream(fileSavePath, FileMode.Create))
                await input.inputFile.CopyToAsync(stream);
            //
            Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies);

            //

            // get the bucket...
            //dynamic oauth = await OAuthController.GetInternalAsync();
            ObjectsApi objects = new ObjectsApi();

            //objects.Configuration.AccessToken = oauth.access_token;
            objects.Configuration.AccessToken = credentials.TokenInternal;

            // upload the file/object, which will create a new object
            dynamic uploadedObj;

            using (StreamReader streamReader = new StreamReader(fileSavePath))
            {
                uploadedObj = await objects.UploadObjectAsync(bucketKey,
                                                              Path.GetFileName(input.inputFile.FileName), (int)streamReader.BaseStream.Length, streamReader.BaseStream,
                                                              "application/octet-stream");
            }

            // cleanup
            System.IO.File.Delete(fileSavePath);// delete server copy

            return(uploadedObj);
        }
        public Task <DataResult <UploadResultData> > UploadAsync(UploadFileInput input)
        {
            /*
             * 传文件流的时候可以不指定FileName,从文件流中读取,指定了优先级更高
             * 传Hash的时候必需指定文件名
             */
            var fileName = input.FileName;

            if (string.IsNullOrWhiteSpace(fileName))
            {
                fileName = input.File?.FileName;
            }
            if (string.IsNullOrWhiteSpace(fileName))
            {
                return(Task.FromResult(new DataResult <UploadResultData>(ResultErrorCodes.Failure, "文件名不能为空")));
            }

            return(_fileUpdSvce.UploadAsync(input, input.File, fileName, input.Hash, input.PeriodMinute));
        }
Пример #6
0
        public async Task <ActionResult <bool> > UploadAsync(UploadFileInput model)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(model.Path))
                {
                    throw new ArgumentNullException(nameof(model.Path));
                }
                if (model.FileBytes == null || model.FileBytes.Length == 0)
                {
                    throw new ArgumentNullException(nameof(model.FileBytes));
                }
                var stream = new System.IO.MemoryStream(model.FileBytes);

                await _fileStore.CreateFileFromStreamAsync(model.Path, stream);

                return(true);
            }
            catch (Exception ex)
            {
                return(BadRequest(ModelState));
                //throw ex;
            }
        }
Пример #7
0
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <exception cref="ApiException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <bool> File_UploadAsync(UploadFileInput model, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/FileStorage/File/UploadAsync");

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(model, _settings.Value));
                    content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json");
                    request_.Content             = content_;
                    request_.Method = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200")
                        {
                            var objectResponse_ = await ReadObjectResponseAsync <bool>(response_, headers_).ConfigureAwait(false);

                            return(objectResponse_.Object);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new ApiException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }

                        return(default(bool));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
Пример #8
0
 /// <exception cref="ApiException">A server side error occurred.</exception>
 public bool File_Upload(UploadFileInput model)
 {
     return(System.Threading.Tasks.Task.Run(async() => await File_UploadAsync(model, System.Threading.CancellationToken.None)).GetAwaiter().GetResult());
 }
Пример #9
0
        public async Task <StoredFileDto> UploadAsync([FromForm] UploadFileInput input)
        {
            if (string.IsNullOrWhiteSpace(input.OwnerType))
            {
                ModelState.AddModelError(nameof(input.OwnerType), $"{nameof(input.OwnerType)} must not be null");
            }
            if (string.IsNullOrWhiteSpace(input.OwnerId))
            {
                ModelState.AddModelError(nameof(input.OwnerId), $"{nameof(input.OwnerId)} must not be null");
            }

            if (input.File == null)
            {
                ModelState.AddModelError(nameof(input.File), $"{nameof(input.File)} must not be null");
            }

            if (!ModelState.IsValid)
            {
                throw new AbpValidationException("An error occured");//, ModelState.Keys.Select(k => new ValidationResult(ModelState.Values[k], new List<string>() { k })));
            }
            var owner = await _dynamicRepository.GetAsync(input.OwnerType, input.OwnerId);

            if (owner == null)
            {
                throw new Exception($"Owner not found (type = '{input.OwnerType}', id = '{input.OwnerId}')");
            }

            var uploadedFile = new StoredFileDto();
            var fileName     = input.File.FileName.CleanupFileName();

            if (!string.IsNullOrWhiteSpace(input.PropertyName))
            {
                // single file upload (stored as a property of an entity)
                var property = ReflectionHelper.GetProperty(owner, input.PropertyName);
                if (property == null || property.PropertyType != typeof(StoredFile))
                {
                    throw new Exception(
                              $"Property '{input.PropertyName}' not found in class '{owner.GetType().FullName}'");
                }

                if (property.GetValue(owner, null) is StoredFile storedFile)
                {
                    storedFile.IsVersionControlled = true;
                    var version = await _fileService.GetNewOrDefaultVersionAsync(storedFile);

                    version.FileName = fileName;
                    version.FileType = Path.GetExtension(fileName);
                    await _fileVersionRepository.InsertOrUpdateAsync(version);

                    await using (var fileStream = input.File.OpenReadStream())
                    {
                        await _fileService.UpdateVersionContentAsync(version, fileStream);
                    }

                    // copy to the main todo: remove duplicated properties (filename, filetype), add a link to the last version and update it using triggers
                    storedFile.FileName = version.FileName;
                    storedFile.FileType = version.FileType;
                    await _fileRepository.UpdateAsync(storedFile);
                }
                else
                {
                    await using (var fileStream = input.File.OpenReadStream())
                    {
                        storedFile = await _fileService.SaveFile(fileStream, fileName);

                        property.SetValue(owner, storedFile, null);
                    }
                }

                await _unitOfWorkManager.Current.SaveChangesAsync();

                MapStoredFile(storedFile, uploadedFile);
            }
            else
            {
                // add file as an attachment (linked to an entity using OwnerType and OwnerId)
                await using (var fileStream = input.File.OpenReadStream())
                {
                    var storedFile = await _fileService.SaveFile(fileStream, fileName, file =>
                    {
                        file.SetOwner(input.OwnerType, input.OwnerId);
                        file.Category = input.FilesCategory;
                    });

                    await _unitOfWorkManager.Current.SaveChangesAsync();

                    MapStoredFile(storedFile, uploadedFile);
                }
            }

            /*
             * 1. property of entity (ownerid+type+property)
             * 2. attachments list (ownerid+type+category)
             * 3. direct upload using id (id)
             */

            return(uploadedFile);
        }