Exemple #1
0
        /// <summary>
        /// 上传
        /// </summary>
        /// <returns>异步则返回进程ID,同步返回上传文件的路径</returns>
        public string Upload()
        {
            HttpRequest request = HttpContext.Current.Request;
            String baseDir = AppDomain.CurrentDomain.BaseDirectory;
            string[] process = request.Form["upload_process"].Split('|');
            string processID = process[1],
                field = process[0];

            var postedFile = request.Files[field];
            if (postedFile == null)
            {
                return null;
            }
            string fileExt = postedFile.FileName.Substring(postedFile.
                FileName.LastIndexOf('.') + 1); //扩展名

            _fileInfo = new UploadFileInfo
            {
                Id = processID,
                ContentLength = postedFile.ContentLength,
                FilePath = String.Format("{0}{1}.{2}", this._saveAbsoluteDir, _fileName, fileExt)
            };

            InitUplDirectory(baseDir, this._saveAbsoluteDir);
            saveStream(postedFile, baseDir + _fileInfo.FilePath);

            return _fileInfo.FilePath;
        }
        public static UploadFileInfo FileUploading(HttpPostedFileBase file, string filePath, int id)
        {
            UploadFileInfo fileInfo = new UploadFileInfo();
            string rvPath = "";
            if (file != null)
            {

                string uploadLocation = "";

                var companyId = id;
                //Logo Store Location
                //Virtual Directory
                var severPath = filePath + companyId;// @"~/UploadOverTime/OverTime/"
                fileInfo.FilePath = severPath.Replace("~", "..") + "/" +DateTime.Today.ToShortDateString().Remove('/')+"_"+file.FileName;
                fileInfo.FileName = file.FileName;
                fileInfo.Extention = FileExtention.GetExtention(file);
                //Creating Directory If Not exist
                Utilities.Common.Helper.Utility.GetUploadPath(severPath);
                var fileName = Path.GetFileName(file.FileName);
                var physicalPath = Path.Combine(HttpContext.Current.Server.MapPath(severPath), fileName);
                file.SaveAs(physicalPath);

            }
            return fileInfo;
        }
Exemple #3
0
 public IActionResult ExistChunks(UploadFileInfo fileInfo)
 {
     Console.WriteLine($"Get[{fileInfo.Hash}] hash");
     return(Json(
                new {
         existChunks = new string[] {
             "517a7af1baf71961c59df93748883f8c",
             "8915cffa187536bea69e96087840e24b",
             "2b242305657669477b394dcbffdad864",
             "16a7b36a5d83079ed334be306219d5f1",
             "f617d7db019813e58a17b330f9245b76",
             "0398043b0a85cd4f61ddfb9c6d9e0a83",
             "9d2253c714337866393e7cdc0e9cdeca"
         }
     }));
 }
Exemple #4
0
        /// <summary>
        /// 新增附件
        /// </summary>
        /// <param name="objectTypeId">附件对象类型ID</param>
        /// <param name="file">附件信息</param>
        /// <returns>附件信息</returns>
        public UploadFileInfo AddFile(int objectTypeId, UploadFileInfo file)
        {
            sqlStr = string.Format("INSERT INTO tbl{0}File ({0}ID,FileType,FileName,FileDesc,AddDate)" +
                                   " VALUES(@ObjectID,@FileType,@FileName,@FileDesc,@AddDate) SELECT @@IDENTITY", LookupManager.GetObjectTypeKey(objectTypeId));

            using (SqlCommand command = ConnectionUtil.GetCommand(sqlStr))
            {
                command.Parameters.Add("@ObjectID", SqlDbType.Int).Value      = SQLUtil.ConvertInt(file.ObjectID);
                command.Parameters.Add("@FileType", SqlDbType.Int).Value      = SQLUtil.ConvertInt(file.FileType);
                command.Parameters.Add("@FileName", SqlDbType.VarChar).Value  = SQLUtil.TrimNull(file.FileName);
                command.Parameters.Add("@FileDesc", SqlDbType.NVarChar).Value = SQLUtil.TrimNull(file.FileDesc);
                command.Parameters.Add("@AddDate", SqlDbType.DateTime).Value  = DateTime.Now;

                file.ID = SQLUtil.ConvertInt(command.ExecuteScalar());
            }
            return(file);
        }
        public async Task <UploadFileInfo> AppendFileAsync(IFormFile file, string sOperator, string sDirectoryName = null)
        {
            UploadFileInfo uploadFileInfo = new UploadFileInfo();

            if (file != null)
            {
                sDirectoryName = string.IsNullOrWhiteSpace(sDirectoryName) ? $"uploads\\{DateTime.Now.ToString("yyyyMMdd")}\\" : sDirectoryName;
                string sFileType = Path.GetExtension(file.FileName);
                //目录
                string sDirectoryPath = _hostEnvironment.ContentRootPath + "\\wwwroot\\" + sDirectoryName;
                // string sDirectoryPath = "\\" + sDirectoryName;

                //新文件名
                string sFileName = Guid.NewGuid().ToString("N") + sFileType;
                //完整路径
                string sFullPath = sDirectoryPath + sFileName;
                //相对路径
                string sRelativePath = string.Format("/{1}{0}", sFileName, sDirectoryName.Replace("\\", "/"));
                if (!Directory.Exists(sDirectoryPath))
                {
                    Directory.CreateDirectory(sDirectoryPath);
                }
                uploadFileInfo.SfileName         = sFileName;
                uploadFileInfo.SfilePath         = sFullPath;
                uploadFileInfo.SfileType         = sFileType;
                uploadFileInfo.SoriginalFileName = Path.GetFileName(file.FileName);
                uploadFileInfo.Isize             = Convert.ToInt32(file.Length);
                uploadFileInfo.SrelativePath     = sRelativePath;
                uploadFileInfo.Uid = System.Guid.NewGuid();
                try
                {
                    Stream stream = new FileStream(sFullPath, FileMode.Create);
                    file.CopyTo(stream);
                    await _UploadFileInfoRepository.AppendAsync(uploadFileInfo, sOperator);

                    await file.CopyToAsync(stream);

                    stream.Dispose();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
            return(uploadFileInfo);
        }
        public async Task <FileUploaded> UploadFile(
            string bucketName,
            string bucketUrl,
            string objectKey,
            S3StorageClass storageClass,
            S3CannedACL permissions, UploadFileInfo file)
        {
            FileUploaded model = new FileUploaded();

            try
            {
                PutObjectRequest request = new PutObjectRequest
                {
                    BucketName   = bucketName,
                    Key          = objectKey,
                    StorageClass = storageClass,
                    CannedACL    = permissions,
                    ContentType  = file.MimeType
                };

                request.InputStream = file.FileConent;

                //MD-HASH
                byte[] md5Hash = file.FileConent.Md5Hash();
                request.MD5Digest = md5Hash.ToBase64String();

                PutObjectResponse response = await S3Clinet.PutObjectAsync(request);

                string eTag         = response.ETag.Trim('"').ToLowerInvariant();
                string expectedETag = md5Hash.ToS3ETagString();

                if (eTag != expectedETag)
                {
                    throw new Exception("The eTag received from S3 doesn't match the eTag computed before uploading. This usually indicates that the file has been corrupted in transit.");
                }

                model.ObjectKey = objectKey;
                //model.ETag = eTag;
                model.ObjectLocation = bucketUrl + objectKey;
            }
            catch (Exception ex)
            {
                model.Exception = ex;
            }
            return(model);
        }
Exemple #7
0
        public bool ScaledImageCreate(UploadFileInfo file)
        {
            string      file_path         = this.upload_dir + file.name;
            string      new_file_path     = file.dir + file.name;
            Image       img               = Image.FromFile(file_path);
            string      fileNameExtension = Path.GetExtension(file_path).ToLower();
            ImageFormat imageType         = GetImageType(fileNameExtension);

            if (img == null)
            {
                return(false);
            }
            int img_width  = img.Width;
            int img_height = img.Height;

            if (img_width < 1 || img_height < 1)
            {
                return(false);
            }

            float scale = Math.Min(file.width / (float)img_width, file.height / (float)img_height);

            int new_width  = (int)Math.Round(img_width * scale, 0);
            int new_height = (int)Math.Round(img_height * scale, 0);

            Bitmap   new_image = new Bitmap(new_width, new_height);
            Graphics g         = Graphics.FromImage(new_image);

            g.SmoothingMode     = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode   = PixelOffsetMode.HighQuality;

            foreach (PropertyItem pItem in img.PropertyItems)
            {
                new_image.SetPropertyItem(pItem);
            }

            g.DrawImage(img, new Rectangle(0, 0, new_width, new_height));

            img.Dispose();

            new_image.Save(new_file_path, imageType);
            new_image.Dispose();

            return(true);
        }
Exemple #8
0
        public void TestUpload4()
        {
            string filePath = "E:/Test/dashboard.ejs";

            UploadFileInfo info = new UploadFileInfo();

            info.Name      = "兔斯基";
            info.Remark    = "qwert";
            info.MD5Hash   = Hasher.GetFileMD5Hash(filePath);
            info.LocalPath = filePath;

            var result = CallerFactory <IAttachmentService> .GetInstance(CallerType.WebApi).Upload(info);

            var attachment = result;

            Assert.AreEqual(info.Name, attachment.Name);
        }
Exemple #9
0
        public List <UploadFileInfo> getUploadList(String cOrgID, String cDir)
        {
            List <UploadFileInfo> KeyList = new List <UploadFileInfo>();

            if (String.IsNullOrEmpty(cDir))
            {
                cDir = "Upload";
            }
            List <String> sqls = new List <string>();
            String        cFileName;
            String        cFileUrl;

            String cKeyID   = AutoID.getAutoID();
            String cAppDir  = System.Web.HttpContext.Current.Server.MapPath("~/");
            String cFileDir = cAppDir + cDir + "\\";

            if (!Directory.Exists(cFileDir))
            {
                Directory.CreateDirectory(cFileDir);
            }
            cFileDir = cFileDir + cKeyID.Substring(0, 8) + "\\";
            if (!Directory.Exists(cFileDir))
            {
                Directory.CreateDirectory(cFileDir);
            }
            for (int i = 0; i < System.Web.HttpContext.Current.Request.Files.Count; i++)
            {
                cKeyID = AutoID.getAutoID();
                UploadFileInfo vUpload = new UploadFileInfo();
                HttpPostedFile vf      = System.Web.HttpContext.Current.Request.Files[i];
                cFileName = Path.GetFileName(vf.FileName);
                String cFileExt = Path.GetExtension(vf.FileName);

                vf.SaveAs(cFileDir + cKeyID + cFileExt);
                cFileUrl         = "/" + cDir + "/" + cKeyID.Substring(0, 8) + "/" + cKeyID + cFileExt;
                vUpload.FileName = cFileName;
                vUpload.ID       = cKeyID;
                vUpload.ORG_ID   = cOrgID;
                vUpload.ResID    = cKeyID;
                vUpload.Url      = cFileUrl;
                log4net.WriteLogFile("getUploadList:" + cOrgID + ":" + cKeyID);
                KeyList.Add(vUpload);
            }
            return(KeyList);
        }
Exemple #10
0
        /// <summary>
        /// 获取文件信息
        /// </summary>
        /// <param name="filepath">文件路径</param>
        /// <param name="regexString">需要匹配的正则表达式</param>
        /// <returns>文件信息</returns>
        public static UploadFileInfo GetFileInfo(string filepath, string regexString)
        {
            ValidateOperator.Begin().NotNullOrEmpty(filepath, "文件路径").IsFilePath(filepath).NotNullOrEmpty(regexString, "正则表达式");
            Match _uploadfolder = Regex.Match(filepath, regexString, RegexOptions.IgnoreCase);

            if (_uploadfolder.Success)
            {
                UploadFileInfo _fileInfo = new UploadFileInfo();
                _fileInfo.Root        = _uploadfolder.Groups[1].Value;
                _fileInfo.Folder      = _uploadfolder.Groups[2].Value;
                _fileInfo.SubFolder   = _uploadfolder.Groups[3].Value;
                _fileInfo.FileName    = _uploadfolder.Groups[4].Value;
                _fileInfo.FileNameExt = _uploadfolder.Groups[5].Value;
                return(_fileInfo);
            }

            return(null);
        }
        /// <summary>
        /// 获取指定的UploadFileInfo实体对象
        /// </summary>
        public static UploadFileInfo GetModel(Expression <Func <UploadFileInfo, bool> > predicate)
        {
            var parser    = new PredicateParser();
            var where_str = parser.Parse(predicate);

            var sql = new StringBuilder();

            sql.Append("SELECT TOP 1 * FROM [UploadFileInfo] ");
            sql.Append(" WHERE " + where_str);
            UploadFileInfo ret = null;

            using (var conn = GetOpenConnection())
            {
                ret = conn.QueryFirstOrDefault <UploadFileInfo>(sql.ToString());
            }

            return(ret);
        }
        public async Task <IActionResult> Upload()
        {
            await Task.Delay(3000);

            var code = Web.GetParam("code");
            var name = Web.GetParam("name");
            var file = Web.GetFile();
            var path = await FileStore.SaveAsync();

            var result = new UploadFileInfo {
                Id   = Id.Guid(),
                Name = file.FileName,
                Size = file.Length,
                Type = file.ContentType,
                Url  = path
            };

            return(Success(result));
        }
Exemple #13
0
        protected virtual void SaveOriginal(FilesItem filesItem, UploadFileInfo uploadFile)
        {
            string path = Path.Combine(SavePath, $"{Guid.NewGuid()}_{Original}{uploadFile.Extension}");

            using (var newStream = new FileStream(UploadSettings.WebRootPath + path, FileMode.OpenOrCreate))
            {
                uploadFile.FileStream.CopyTo(newStream);
            }
            filesItem.O = new()
            {
                Length   = uploadFile.Length,
                Name     = uploadFile.FileName,
                FullPath = $"{UploadSettings.UriPath.TrimEnd('/')}/{path.Replace("\\", "/").TrimStart('/')}",
                UriPath  = UploadSettings.UriPath,
                Path     = path,
                Suff     = uploadFile.Extension,
                No       = Uploads.Files.Count
            };
        }
Exemple #14
0
        /// <summary>
        /// 保存表单文件,根据HttpPostedFile
        /// </summary>
        /// <param name="postFile">HttpPostedFile</param>
        /// <returns>上传返回信息</returns>
        private OperatedResult <UploadFileInfo> SaveUploadFile(HttpPostedFile postFile)
        {
            try
            {
                CheckResult <string> _checkedFileParamter = CheckedFileParamter(postFile);

                if (!_checkedFileParamter.State)
                {
                    return(OperatedResult <UploadFileInfo> .Fail(_checkedFileParamter.Message));
                }

                string _fileName = _checkedFileParamter.Data;
                string _webDir   = string.Empty;
                // 获取存储目录
                string _directory = this.GetDirectory(ref _webDir),
                       _filePath  = _directory + _fileName;

                if (File.Exists(_filePath))
                {
                    if (uploadFileSetting.IsRenameSameFile)
                    {
                        _filePath = _directory + DateTime.Now.FormatDate(12) + "-" + _fileName;
                    }
                    else
                    {
                        File.Delete(_filePath);
                    }
                }

                // 保存文件
                postFile.SaveAs(_filePath);
                UploadFileInfo _uploadFileInfo = new UploadFileInfo();
                _uploadFileInfo.FilePath    = _filePath;
                _uploadFileInfo.FilePath    = _webDir + _fileName;
                _uploadFileInfo.FileName    = _fileName;
                _uploadFileInfo.WebFilePath = _webDir + _fileName;
                return(OperatedResult <UploadFileInfo> .Success(_uploadFileInfo));
            }
            catch (Exception ex)
            {
                return(OperatedResult <UploadFileInfo> .Fail(ex.Message));
            }
        }
        /// <summary>
        /// 获取文件信息
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="updateFileList"></param>
        /// <param name="fileSize"></param>
        /// <param name="fileCount"></param>
        private void GetFileInfo(string folderPath, ref List <UploadFileInfo> updateFileList, ref long fileSize, ref long fileCount)
        {
            UploadFileInfo updateFileInfo;
            string         filePath = string.Empty;

            try
            {
                DirectoryInfo        dir          = new DirectoryInfo(folderPath);
                System.IO.FileInfo[] fileInfoList = dir.GetFiles();
                DirectoryInfo[]      dirInfo      = dir.GetDirectories();

                if (fileInfoList.Length > 0)
                {
                    foreach (System.IO.FileInfo fi in fileInfoList)
                    {
                        updateFileInfo = new UploadFileInfo();
                        filePath       = fi.FullName;

                        updateFileInfo.FileName     = fi.Name;
                        updateFileInfo.FileSize     = fi.Length;
                        updateFileInfo.RelativePath = filePath.Substring(this.rootFolderPath.Length, filePath.Length - this.rootFolderPath.Length - fi.Name.Length);
                        updateFileInfo.PhysicalPath = filePath;

                        updateFileList.Add(updateFileInfo);

                        fileSize += fi.Length;
                        fileCount++;
                    }
                }
                if (dirInfo.Length > 0)
                {
                    foreach (DirectoryInfo di in dirInfo)
                    {
                        this.GetFileInfo(di.FullName, ref updateFileList, ref fileSize, ref fileCount);
                    }
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.ErrorLog("AutoUpdateServerManagement.AutoUpdateServiceManager.GetFileInfo", ex);
                throw ex;
            }
        }
Exemple #16
0
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="info">附件信息</param>
        /// <returns>附件信息</returns>
        public JsonResult UploadFile(UploadFileInfo info)
        {
            if (CheckSession(false) == false)
            {
                return(Json(ResultModelBase.CreateTimeoutModel(), JsonRequestBehavior.AllowGet));
            }
            if (CheckSessionID() == false)
            {
                return(Json(ResultModelBase.CreateLogoutModel(), JsonRequestBehavior.AllowGet));
            }

            ResultModel <int> result = new ResultModel <int>();

            try
            {
                if (string.IsNullOrEmpty(info.FileContent))
                {
                    result.SetFailed(ResultCodes.BusinessError, "文件为空");
                }
                else
                {
                    if (info.ObjectID == 0)
                    {
                        if (info.ID != 0)
                        {
                            DeleteUploadFileInSession(info.ID);
                        }

                        result.Data = SaveUploadFileInSession(info);
                    }
                    else
                    {
                        result.Data = this.fileManager.SaveUploadFile(info).ID;
                    }
                }
            }
            catch (Exception ex)
            {
                NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message);
                result.SetFailed(ResultCodes.SystemError, ControlManager.GetSettingInfo().ErrorMessage);
            }
            return(JsonResult(result));
        }
Exemple #17
0
        public void TestUploadSingleFile()
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\tsj192.jpg";

            UploadFileInfo info = new UploadFileInfo();

            info.Name      = "兔斯基";
            info.Remark    = "8dfs";
            info.LocalPath = filePath;
            info.MD5Hash   = Hasher.GetFileMD5Hash(filePath);

            var task = CallerFactory <IAttachmentService> .GetInstance(CallerType.WebApi).UploadAsync(info);

            //task.ContinueWith<Attachment>(r => Console)

            var attachment = task.Result;

            Assert.AreEqual(info.Name, attachment.Name);
        }
Exemple #18
0
        /// <summary>
        /// 根据作业报告id获取作业报告信息
        /// </summary>
        /// <param name="dispatchReportID">作业报告编号</param>
        /// <returns>作业报告信息</returns>
        public DispatchReportInfo GetDispatchReportByID(int dispatchReportID)
        {
            DispatchReportInfo dispatchReport = dispatchReportDao.GetDispatchReportByID(dispatchReportID);
            DispatchInfo       dispatchInfo   = this.dispatchDao.GetDispatchByID(dispatchReport.Dispatch.ID);

            dispatchReport.Dispatch = dispatchInfo.Copy4Base();
            if (dispatchReport != null)
            {
                UploadFileInfo fileInfo = this.fileDao.GetFile(ObjectTypes.DispatchReport, dispatchReport.ID);
                if (fileInfo != null)
                {
                    dispatchReport.FileInfo = fileInfo;
                }
                else
                {
                    dispatchReport.FileInfo = new UploadFileInfo();
                }

                List <HistoryInfo> histories = this.historyDao.GetHistories(ObjectTypes.DispatchReport, dispatchReport.ID);
                if (histories != null && histories.Count > 0)
                {
                    foreach (HistoryInfo history in histories)
                    {
                        history.Action.Name = DispatchReportInfo.Actions.GetDesc(history.Action.ID);
                    }
                    dispatchReport.Histories = histories;
                    dispatchReport.SetHis4Comments();
                }

                dispatchReport.ReportComponent = dispatchReportDao.GetReportComponentByDispatchReportID(dispatchReport.ID);
                if (dispatchReport.ReportComponent.Count > 0)
                {
                    foreach (ReportComponentInfo component in dispatchReport.ReportComponent)
                    {
                        component.FileInfos = this.fileDao.GetFiles(ObjectTypes.ReportAccessory, component.ID);
                    }
                }
                dispatchReport.ReportConsumable = dispatchReportDao.GetReportConsumableByDispatchReportID(dispatchReport.ID);
                dispatchReport.ReportService    = dispatchReportDao.GetReportServiceByDispatchReportID(dispatchReport.ID);
            }
            return(dispatchReport);
        }
Exemple #19
0
        public UploadFileInfo SaveUploadFile(UploadFileInfo info)
        {
            info.FileName = new FileInfo(info.FileName).Name;
            if (info.ID > 0)
            {
                UploadFileInfo existingInfo = this.fileDao.GetFileByID(info.ObjectTypeId, info.ID);
                FileUtil.DeleteFile(ObjectTypes.GetFileFolder(info.ObjectTypeId), existingInfo.GetFileName());

                fileDao.UpdateFile(info.ObjectTypeId, info);
            }
            else
            {
                info = fileDao.AddFile(info.ObjectTypeId, info);
            }

            byte[] fileContent = Convert.FromBase64String(info.FileContent);
            FileUtil.SaveFile(fileContent, ObjectTypes.GetFileFolder(info.ObjectTypeId), info.GetFileName());

            return(info);
        }
Exemple #20
0
        /// <summary>
        /// 根据合同id获取合同信息
        /// </summary>
        /// <param name="id">合同编号</param>
        /// <returns>合同信息</returns>
        public ContractInfo GetContract(int id)
        {
            ContractInfo info = this.contractDao.GetContractByID(id);

            if (info != null)
            {
                UploadFileInfo fileInfo = this.fileDao.GetFile(ObjectTypes.Contract, info.ID);
                if (fileInfo != null)
                {
                    info.ContractFile = fileInfo;
                }
                else
                {
                    info.ContractFile = new UploadFileInfo();
                }
                info.Equipments = this.contractDao.GetContractEqpts(info.ID);
            }

            return(info);
        }
Exemple #21
0
        public UploadFileResult UploadFile(UploadFileInfo uploadFile)
        {
            string path = string.Empty;

            if (string.IsNullOrEmpty(this.filePath))
            {
                path = uploadFile.PhysicalPath;
            }
            else
            {
                path = path + uploadFile.RelativePath;
            }

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

            return(this.SaveUploadFile(uploadFile, path));
        }
Exemple #22
0
        /// <summary>
        /// 保存上传的附件信息至session
        /// </summary>
        /// <param name="file">附件信息</param>
        /// <returns>附件编号</returns>
        public int SaveUploadFileInSession(UploadFileInfo file)
        {
            if (Session[SESSION_KEY_FILES] == null)
            {
                Session[SESSION_KEY_FILES] = new List <UploadFileInfo>();
            }

            int id = -1;
            List <UploadFileInfo> files = (List <UploadFileInfo>)Session[SESSION_KEY_FILES];

            if (files.Count > 0)
            {
                id = (from UploadFileInfo temp in files select temp.ID).Min() - 1;
            }

            file.ID = id;
            files.Add(file);

            return(file.ID);
        }
Exemple #23
0
        /// <summary>
        /// 获取下载附件时的文件名
        /// </summary>
        /// <param name="info">附件信息</param>
        /// <returns>格式化后的附件名</returns>
        public string GetDownloadFileName(UploadFileInfo info)
        {
            string name = info.GetDisplayFileName();

            if (name == "")
            {
                return(info.FileName);
            }

            if (ObjectTypes.Equipment.Equals(info.ObjectTypeId))
            {
                EquipmentInfo equipmentInfo = this.equipmentDao.GetEquipmentByID(info.ObjectID);
                name = string.Format("{0}_{1}", name, equipmentInfo.AssetCode);
            }
            else
            {
                name = string.Format("{0}_{1}", LookupManager.GetObjectOID(info.ObjectTypeId, info.ObjectID), name);
            }

            return(name + new FileInfo(info.FileName).Extension);
        }
        public static Video Upload(Item accountItem, UploadFileInfo uploadFileInfo)
        {
            var args = new VideoUploadArgs
            {
                Service = Service.GetExecutor(accountItem, uploadFileInfo)
            };

            try
            {
                args.Service.Start();
                Sitecore.Pipelines.CorePipeline.Run("Brightcove.VideoUpload", args);
                args.Service.EndWithSuccess();
            }
            catch (Exception ex)
            {
                args.Service.EndWithError(ex);
                throw;
            }

            return(args.Video);
        }
        /// <summary>
        /// puts the file uploading task to the queue
        /// </summary>
        /// <param name="pathToFile">path to file</param>
        /// <param name="queryParams">query parameters to pass to the server</param>
        /// <param name="fileUploadUrl">uri to upload file to (FileUploadUrl is used as default)</param>
        /// <param name="fileParameterName">server-side parameter name for a file (FileParameterName is used as default)</param>
        /// <param name="additionalInfo">any information that will be stored along with the file and passed back in </param>
        public void QueueFileUpload(string pathToFile,
                                    string queryParams       = "",
                                    string fileUploadUrl     = null,
                                    string fileParameterName = null,
                                    string additionalInfo    = null)
        {
            if (string.IsNullOrEmpty(FileUploadUrl) && string.IsNullOrEmpty(fileUploadUrl))
            {
                throw new InvalidOperationException(
                          $"Either {nameof(fileUploadUrl)} parameter or {nameof(FileUploadUrl)} property must be specified");
            }

            if (string.IsNullOrEmpty(fileParameterName) && string.IsNullOrEmpty(FileParameterName))
            {
                throw new InvalidOperationException(
                          $"Either {nameof(fileParameterName)} parameter or {nameof(FileParameterName)} property must be specified");
            }

            var realm = CreateRealmius();

            Uri    uri1         = new Uri(pathToFile);
            Uri    uri2         = new Uri(FileSystem.Current.LocalStorage.Path + "/");
            string relativePath = uri2.MakeRelativeUri(uri1).ToString();

            var fileInfo = new UploadFileInfo()
            {
                Added             = DateTimeOffset.Now,
                Url               = fileUploadUrl ?? FileUploadUrl,
                QueryParams       = queryParams,
                PathToFile        = relativePath,
                FileParameterName = fileParameterName ?? FileParameterName,
                AdditionalInfo    = additionalInfo
            };

            realm.Write(
                () =>
            {
                realm.Add(fileInfo);
            });
        }
Exemple #26
0
        // 初始化信息
        void Init(HttpContext context)
        {
            string fileName = context.Request.Files[0].FileName;

            this.ctx = context;
            isLog    = string.IsNullOrEmpty(ctx.Request.Form["IsLog"]) ? false : bool.Parse(ctx.Request.Form["IsLog"]);

            long   fileLength = string.IsNullOrEmpty(ctx.Request.Form["FileLength"]) ? 0 : long.Parse(ctx.Request.Form["FileLength"]);
            string src        = ctx.Request.Form["src"];
            string filename   = ctx.Request.Form["filename"];

            if (string.IsNullOrWhiteSpace(filename))
            {
                filename = ctx.Request.Files[0].FileName.Split('\\').Last();
            }
            if (fileLength == 0)
            {
                fileLength = ctx.Request.Files[0].ContentLength;
            }



            // 客户端最后写入时间,考虑到效率,据此简单判断客户端文件是否改变,断点续传时使用(如用HashCode对大文件影响效率)
            //string clientLastWriteFileTime = Func.AttrIsNull(ctx.Request.Form["LastWriteFileTime"]) ? String.Empty : ctx.Request.Form["LastWriteFileTime"];

            // 获取文件信息状态
            //fileInfo = new UploadFileInfo(userState.UserId, filename, clientLastWriteFileTime, fileSize);
            uploadConfig = UploadHelper.RetrieveConfig();
            fileInfo     = new UploadFileInfo("USERID", filename, fileLength);

            // 开始上传
            long startByte = string.IsNullOrEmpty(ctx.Request.Form["StartByte"]) ? 0 : long.Parse(ctx.Request.Form["StartByte"]);
            // 并不是获取上传字节
            bool getBytes = string.IsNullOrEmpty(context.Request.Form["GetBytes"]) ? false : bool.Parse(context.Request.Form["GetBytes"]);

            if (startByte == 0 && !getBytes)
            {
                this.WriteLog("Upload Begin");
            }
        }
Exemple #27
0
        private string UploadMaterial_news(CT_Wechat_Multimedium _Multimed)
        {
            CT_Campaigns _cam = _b_cam.GetCampaign(_Multimed.WM_CG_EV_Code);

            if (_cam == null)
            {
                return(null);
            }
            string _Id_thumb = GetMaterialId_thumb(_Multimed.WM_CG_EV_Code, _Multimed.WM_fileName);

            if (string.IsNullOrEmpty(_Id_thumb))
            {
                return(null);
            }
            High_news _new = new High_news()
            {
                thumb_media_id = _Id_thumb,
                title          = _cam.CG_Desc,
                content        = _Multimed.WM_Media.Replace('"', '\''),
            };
            IList <High_news> _Ihigh = new List <High_news>();

            _Ihigh.Add(_new);
            string _news = wechatHandle.High_news(_Ihigh);

            if (string.IsNullOrEmpty(_news))
            {
                return(null);
            }
            UploadFileInfo _u = wechatHandle.UploadImageText(_news);

            if (_u == null)
            {
                return(null);
            }
            int i = _d_wechat.UpdateMultimedium(_Multimed.WM_CG_EV_Code, _Multimed.WM_CG_EV_Type, _Multimed.WM_Tpe, _Multimed.WM_fileName, _u.MediaId, _u.Invalidation);

            return(_u.MediaId);
        }
Exemple #28
0
        public ActionResult ViewPDF(int equipmentID, int fileID)
        {
            if (CheckSession() == false)
            {
                return(Json(ResultModelBase.CreateTimeoutModel(), JsonRequestBehavior.AllowGet));
            }
            if (CheckSessionID() == false)
            {
                return(Json(ResultModelBase.CreateLogoutModel(), JsonRequestBehavior.AllowGet));
            }
            ResultModelBase result = new ResultModelBase();

            try
            {
                UploadFileInfo info = this.fileDao.GetFileByID(ObjectTypes.Equipment, fileID);

                FileUtil.CheckDirectory(Constants.EquipmentFolder);

                string filePath = Path.Combine(Constants.EquipmentFolder, string.Format("{0}_{1}{2}", equipmentID, fileID, new FileInfo(info.FileName).Extension));


                if (info != null && System.IO.File.Exists(filePath))
                {
                    Stream stream = new FileStream(filePath, FileMode.Open);
                    return(File(stream, info.FileName));
                }
                else
                {
                    result.SetFailed(ResultCodes.BusinessError, "文件不存在");
                }
            }
            catch (Exception ex)
            {
                NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message);
                result.SetFailed(ResultCodes.SystemError, ControlManager.GetSettingInfo().ErrorMessage);
            }

            return(View("ErrorPage", null, result.ResultMessage));
        }
Exemple #29
0
        /// <summary>
        ///  下载附件
        /// </summary>
        /// <param name="objectTypeId">附件对象类型ID</param>
        /// <param name="id">附件编号</param>
        /// <returns>附件信息</returns>
        public ActionResult DownloadUploadFile(int objectTypeId, int id)
        {
            if (CheckSession(false) == false)
            {
                return(Json(ResultModelBase.CreateTimeoutModel(), JsonRequestBehavior.AllowGet));
            }
            if (CheckSessionID() == false)
            {
                return(Json(ResultModelBase.CreateLogoutModel(), JsonRequestBehavior.AllowGet));
            }

            try
            {
                if (id < 0)
                {
                    UploadFileInfo file = GetUploadFileInSession(id);

                    string fileName    = new FileInfo(file.FileName).Name;
                    byte[] fileContent = Convert.FromBase64String(file.FileContent);

                    return(File(fileContent, System.Web.MimeMapping.GetMimeMapping(fileName), fileName));
                }
                else
                {
                    string         filePath = null;
                    UploadFileInfo file     = this.fileDao.GetFileByID(objectTypeId, id);
                    filePath = Path.Combine(ObjectTypes.GetFileFolder(objectTypeId), file.GetFileName());
                    Response.AddHeader("Set-Cookie", "fileDownload=true; path=/");
                    file.FileName = this.fileManager.GetDownloadFileName(file);
                    return(File(filePath, System.Web.MimeMapping.GetMimeMapping(file.FileName), file.FileName));
                }
            }
            catch (Exception ex)
            {
                NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message);
            }

            return(null);
        }
Exemple #30
0
        /// <summary>
        ///  转换上传的素材 1=图片,2=语音,3=视频,4=缩略图,
        /// </summary>
        /// <param name="type"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static UploadFileInfo ConvertMaterial(int type, string fileName)
        {
            UploadFileInfo _FileInfo = null;

            if (type == 1)
            {
                _FileInfo = ConvertMaterial(MaterialType.image, fileName);
            }
            else if (type == 2)
            {
                _FileInfo = ConvertMaterial(MaterialType.voice, fileName);
            }
            else if (type == 3)
            {
                _FileInfo = ConvertMaterial(MaterialType.video, fileName);
            }
            else if (type == 4)
            {
                _FileInfo = ConvertMaterial(MaterialType.thumb, fileName);
            }
            return(_FileInfo);
        }
        /// <summary>
        /// 同步上传单个附件
        /// </summary>
        /// <param name="data">上传附件信息</param>
        /// <returns></returns>
        public Attachment Upload(UploadFileInfo data)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    //表明是通过multipart/form-data的方式上传数据
                    using (var content = new MultipartFormDataContent())
                    {
                        content.Headers.ContentType.CharSet = "utf-8";
                        var fileContent = SetFileContent(data);
                        content.Add(fileContent);

                        var formContent = SetFormContent(data);
                        foreach (var byteContent in formContent)
                        {
                            content.Add(byteContent);
                        }

                        string url = this.host + "attachment/async-upload";

                        var response = client.PostAsync(url, content).Result;

                        response.EnsureSuccessStatusCode();
                        var entity = response.Content.ReadAsAsync <Attachment>().Result;

                        return(entity);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Instance.Exception("同步上传附件异常", e);
                return(null);
            }
        }
Exemple #32
0
        public void CheckAndSaveImage(PostInfo obj, HttpFileCollectionBase files)
        {
            if (files == null || files.Count == 0)
            {
                return;
            }

            HttpPostedFileBase file = files[0];

            if (file.ContentLength == 0)
            {
                return;
            }

            string fileName = string.IsNullOrEmpty(obj.Images) ? obj.ItemKey : obj.Images;

            byte[] bytes = new byte[file.ContentLength];
            using (BinaryReader reader = new BinaryReader(file.InputStream))
            {
                bytes = reader.ReadBytes(file.ContentLength);
            }

            UploadFileInfo info = new UploadFileInfo();

            info.FileName   = fileName;
            info.FileData   = Convert.ToBase64String(bytes);
            info.SaveMethod = string.IsNullOrEmpty(obj.Images) ? "Insert" : "Update";

            ResultDTO <UploadFileInfo> rs = this.InsertOrUpdate(info);

            if (rs.Code < 0)
            {
                _log.Error(rs.Message);
            }
            else
            {
                obj.Images = rs.Data.FileName;
            }
        }
Exemple #33
0
 /// <summary>
 /// 上传文档
 /// </summary>
 /// <param name="file"></param>
 /// <param name="UserID">上传人ID</param>
 /// <param name="TypeID">文档分类型ID</param>
 /// <returns></returns>
 public bool UpLoadDocument(UploadFileInfo file,int UserID,int TypeID)
 {
     return false;
 }