Пример #1
0
        public async Task <JsonResult> UploadFile(UploadFileAddressModel model)
        {
            var app = await _coreApiService.ValidateAccessTokenAsync(model.AccessToken);

            //try find the target bucket
            var targetBucket = await _dbContext.Bucket.FindAsync(model.BucketId);

            if (targetBucket == null || targetBucket.BelongingAppId != app.AppId)
            {
                return(this.Protocal(ErrorType.Unauthorized, "The bucket you try to upload is not your app's bucket!"));
            }
            //try get the file from form
            var file    = Request.Form.Files.First();
            var newFile = new OSSFile
            {
                RealFileName  = Path.GetFileName(file.FileName.Replace(" ", "")),
                FileExtension = Path.GetExtension(file.FileName),
                BucketId      = targetBucket.BucketId,
                AliveDays     = model.AliveDays,
                UploadTime    = DateTime.Now
            };

            //Ensure there not exists file with the same file name.
            lock (_obj)
            {
                var exists = _dbContext.OSSFile.Exists(t => t.RealFileName == newFile.RealFileName && t.BucketId == newFile.BucketId);
                if (exists)
                {
                    return(this.Protocal(ErrorType.HasDoneAlready, "There already exists a file with that name."));
                }
                //Save to database
                _dbContext.OSSFile.Add(newFile);
                _dbContext.SaveChanges();
            }
            //Try saving file.
            string DirectoryPath = _configuration["StoragePath"] + $"{_}Storage{_}{targetBucket.BucketName}{_}";

            if (Directory.Exists(DirectoryPath) == false)
            {
                Directory.CreateDirectory(DirectoryPath);
            }
            using (var fileStream = new FileStream(DirectoryPath + newFile.FileKey + ".dat", FileMode.Create))
            {
                await file.CopyToAsync(fileStream);

                fileStream.Close();
            }
            // Get Internet path
            newFile.InternetPath = new AiurUrl(_serviceLocation.OSS, newFile.BelongingBucket.BucketName, newFile.RealFileName, new { }).ToString();
            //Return json
            return(Json(new UploadFileViewModel
            {
                Code = ErrorType.Success,
                FileKey = newFile.FileKey,
                Message = "Successfully uploaded your file.",
                Path = newFile.InternetPath
            }));
        }
Пример #2
0
        public async Task UploadObject(string bucketKey, OSSFile file)
        {
            string       objectKey = file.Name;
            MemoryStream data      = new MemoryStream(File.ReadAllBytes(file.Path));

            client.BaseUrl = new Uri($"https://developer.api.autodesk.com/oss/v2/buckets/{bucketKey}/objects/{objectKey}");
            request        = new RestRequest(Method.PUT);

            request.AddHeader("Authorization", $"{this.token.TokenType} {this.token.AccessToken}").
            AddHeader("Content-Length", data.Length.ToString()).
            AddParameter("application/octet-stream", data.ToArray(), ParameterType.RequestBody);

            Upload?.Invoke(false, file);
            data.Close();
            IRestResponse response = await client.ExecuteTaskAsync(request);

            while (response.StatusCode != HttpStatusCode.OK)
            {
                Upload?.Invoke(false, file);
            }
            Upload?.Invoke(true, file);
        }
Пример #3
0
        public async Task <JsonResult> UploadFile(CommonAddressModel model)
        {
            var app = await APIService.ValidateAccessTokenAsync(model.AccessToken);

            //try find the target bucket
            var targetBucket = await _dbContext.Bucket.FindAsync(model.BucketId);

            if (targetBucket == null || targetBucket.BelongingAppId != app.AppId)
            {
                return(Json(new AiurProtocal
                {
                    code = ErrorType.Unauthorized,
                    message = "The bucket you try to upload is not your app's bucket!"
                }));
            }
            //try get the file from form
            var file = Request.Form.Files.First();

            if (file == null)
            {
                return(Json(new AiurProtocal
                {
                    code = ErrorType.InvalidInput,
                    message = "Please upload your file!"
                }));
            }
            //Test the extension
            bool validExtension = MIME.MIMETypesDictionary.ContainsKey(Path.GetExtension(file.FileName).Replace(".", ""));

            if (!validExtension)
            {
                return(Json(new AiurProtocal
                {
                    code = ErrorType.InvalidInput,
                    message = "The extension of your file is not supported!"
                }));
            }
            //Save to database
            var newFile = new OSSFile
            {
                RealFileName    = Path.GetFileName(file.FileName.Replace(" ", "")),
                FileExtension   = Path.GetExtension(file.FileName),
                BucketId        = targetBucket.BucketId,
                BelongingBucket = targetBucket,
            };

            _dbContext.OSSFile.Add(newFile);
            await _dbContext.SaveChangesAsync();

            //Try saving file.
            string DirectoryPath = GetCurrentDirectory() + $@"{_}Storage{_}{targetBucket.BucketName}{_}";

            if (Exists(DirectoryPath) == false)
            {
                CreateDirectory(DirectoryPath);
            }
            var fileStream = new FileStream(DirectoryPath + newFile.FileKey + ".dat", FileMode.Create);
            await file.CopyToAsync(fileStream);

            fileStream.Close();
            //Return json
            return(Json(new UploadFileViewModel
            {
                code = ErrorType.Success,
                FileKey = newFile.FileKey,
                message = "Successfully uploaded your file.",
                Path = newFile.GetInternetPath
            }));
        }
Пример #4
0
        public async Task UploadChunkObject(string bucketKey, OSSFile file)
        {
            FileStream data      = File.OpenRead(file.Path);
            var        length    = data.Length;
            string     objectKey = file.Name;

            if (await this.GetBucketObject(bucketKey, objectKey) != null)
            {
                await this.DeleteObject(bucketKey, objectKey);
            }

            string sessionId = "SI" + Path.GetFileNameWithoutExtension(objectKey) + length;

            ObjectsApi api = new ObjectsApi();

            api.Configuration.AccessToken = this.token.AccessToken;

            int chunkSize = 5 * 1024 * 1024;

            long chunkCount = (long)Math.Round(0.5 + ((double)length / (double)chunkSize));

            long dataWrited = 0;

            for (int i = 0; i < chunkCount; i++)
            {
                long startByte = i * chunkSize;

                long next = (i + 1) * chunkSize;

                if (next > length)
                {
                    next = length - 1;
                }
                else
                {
                    next--;
                }

                long byteLength = next - startByte + 1;

                string bytesRange = string.Format("bytes {0}-{1}/{2}", startByte, next, length);
                byte[] buffer     = new byte[byteLength];

                data.Read(buffer, 0, (int)byteLength);
                MemoryStream ms = new MemoryStream(buffer);
                ms.Write(buffer, 0, (int)byteLength);
                ms.Position = 0;

                var response = await api.UploadChunkAsyncWithHttpInfo(bucketKey, objectKey, (int)byteLength, bytesRange, sessionId, ms);

                dataWrited += byteLength;

                double progress = (double)(100 * decimal.Ceiling(dataWrited) / decimal.Ceiling(length));

                if (response.StatusCode == 202)
                {
                    ProgressUpload?.Invoke(false, file, Convert.ToInt32(progress));
                }
                else if (response.StatusCode == 200)
                {
                    Upload?.Invoke(true, file);
                    break;
                }
                else
                {
                    ErrorOccurred("Error occurred while uploading...\nCode: " + response.StatusCode);
                    break;
                }
            }
            data.Close();
        }
Пример #5
0
    public void OSSdownload(DownloadUnit downUnit, OSSFile of, Action <bool> callback)
    {
        //打开上次下载的文件
        long startPos = 0;
        //将文件的后缀名改为临时文件名 .temp
        string tempfilename = downUnit.fileName.Replace(Path.GetExtension(downUnit.fileName), ".temp");
        string tempFile     = downUnit.savePath + "/" + tempfilename;
        string InstallFile  = downUnit.savePath + "/" + downUnit.fileName;

        //若此文件已经存在 则直接返回文件的总大小
        if (File.Exists(InstallFile) && string.Equals(Utility.GetMd5Hash(File.OpenRead(InstallFile)), downUnit.md5))
        {
            //不执行下载流程
            //Debug.LogError("下载的文件 已经存在                 : " + InstallFile);
            if (callback != null)
            {
                callback(true);
            }
            return;
        }
        ///如果本地已经临时文件 获取临时文件的长度  断点续传
        if (System.IO.File.Exists(tempFile))
        {
            FileStream fs = File.OpenWrite(tempFile);
            startPos = fs.Length;
            fs.Seek(startPos, SeekOrigin.Current); //移动文件流中的当前指针
        }
        //必须要GMT时间
        string expire = DateTime.UtcNow.GetDateTimeFormats('r')[0].ToString();

        //Debug.Log(of.endpoint + "            " + of.objectName);
        //Debug.Log("OSS下载 url   @" + downUnit.downUrl + "@ 签名  @" + Utility.OSSSignature(of.endpoint, of.objectName, expire) + "@ 时间 @" + expire);

        HttpBase.OssGet(downUnit.downUrl, new KeyValuePair <string, string>[]
        {
            new KeyValuePair <string, string>("Date", expire),
            new KeyValuePair <string, string>("Authorization", Utility.OSSSignature(of.endpoint, of.objectName, expire)),
            new KeyValuePair <string, string>("Range", "bytes=" + (int)startPos + "-"),
        }, ((originalRequest, response) =>
        {
            //float fileSize = float.Parse(downUnit.size) / (1024 * 1024);
            //originalRequest.ConnectTimeout = new TimeSpan(600000);
            //originalRequest.Timeout = new TimeSpan(600000);
            FileStream fs = null;
            if (response == null)
            {
                // Debug.Log("请求为空" +downUnit.downUrl +" "+ downUnit.fileName);
                if (fs != null)
                {
                    fs.Flush();
                    fs.Close();
                    fs = null;
                }

                if (callback != null)
                {
                    callback(false);
                }

                return;
            }
            if (!response.IsSuccess)
            {
                // Debug.Log("请求失败!" + response.StatusCode + " "+downUnit.downUrl+" "+ downUnit.fileName);
                if (fs != null)
                {
                    fs.Flush();
                    fs.Close();
                    fs = null;
                }

                if (callback != null)
                {
                    callback(false);
                }

                return;
            }
            try
            {
                if (System.IO.File.Exists(tempFile))
                {
                    fs = File.OpenWrite(tempFile);
                }
                else
                {
                    string direName = Path.GetDirectoryName(tempFile);
                    if (!Directory.Exists(direName))
                    {
                        Directory.CreateDirectory(direName);
                    }

                    fs = new FileStream(tempFile, FileMode.Create);
                }

                var resp_bytes = response.Data;
                fs.Write(resp_bytes, 0, resp_bytes.Length);

                fs.Flush();
                fs.Close();
                fs = null;
                response.Dispose();

                if (!File.Exists(InstallFile))
                {
                    File.Move(tempFile, InstallFile);
                }

                var file = File.OpenRead(InstallFile);
                string md5 = Utility.GetMd5Hash(file);
                //Debug.LogError("文件路径 :" + InstallFile + "  /文件名称/     :" + downUnit.fileName +
                //               "    /本地计算的md5值为/    :" + md5 + "            /服务器的md5/    :" + downUnit.md5 +
                //               "         /下载url  /      :" + downUnit.downUrl);
                file.Dispose();
                file.Close();
                fs = null;
                if (md5 == downUnit.md5)
                {
                    //Debug.LogError("下载成功");
                    if (callback != null)
                    {
                        callback(true);
                    }

                    return;
                }
                else
                {
                    File.Delete(InstallFile);
                    //Debug.LogError(
                    //    "删除       删除      删除      删除      删除      删除      删除      删除      删除      删除      删除           " +
                    //    InstallFile);
                    if (callback != null)
                    {
                        callback(false);
                    }

                    return;
                }
            }
            catch (WebException ex)
            {
                Debug.Log("下载出错:");
                if (fs != null)
                {
                    fs.Flush();
                    fs.Close();
                    fs = null;
                }

                if (callback != null)
                {
                    callback(false);
                }

                return;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Flush();
                    fs.Close();
                    fs = null;
                }

                response.Dispose();
            }
        }));
    }