asp.net(c\#)개발 중인 파일 업로드 구성 요소 uploadify 의 사용 방법(진도 표시 줄 포함)

11309 단어 uploadifyasp.net
웹 개발 에 서 는 업로드 할 수 있 는 구성 요소 모듈 이 많 습 니 다.HTML 의 File 컨트롤 을 이용 하여 업로드 하 는 것 도 방법 입 니 다.그러나 이런 방식 은 처리 해 야 할 세부 사항 이 많 고 단일 파일 만 지원 할 수 있 습 니 다.현재 웹 개발 에 많이 사용 되 고 있 는 것 은 uploadiy(참고)일 수 있 습 니 다.http://www.uploadify.com/)하나 라 고 할 수 있 습 니 다.그러나 이 버 전 은 계속 변화 하고 있 습 니 다.그들의 스 크 립 트 호출 도 크게 다 릅 니 다.심지어 호출 과 매개 변수 가 계속 변화 하고 있 습 니 다.아주 일찍 그 Flash 의 버튼 문 자 는 변 하지 않 았 습 니 다.이 수필 은 주로 프로젝트 의 실제 상황 에 따라 달라 집 니 다.3.1 버 전의 uploadify 컨트롤 사용 을 소개 합 니 다.이 버 전 은 아직 최신 버 전이 기 때문에 저희 가 웹 개발 을 하 는 데 참고 가 됩 니 다.
이 컨트롤 은 많은 매개 변수 제어 와 사건 의 처리 응답 이 있어 상대 적 으로 도 사용 하기 좋다.매개 변수 통 제 는 업로드 파일 의 다 중 선택,파일 형식,파일 크기,파일 수량,파일 의 존재 여 부 를 검사 하고 일부 단추 매개 변수 에 대한 통 제 를 제어 할 수 있 습 니 다.예 를 들 어 문자,높이,너비 등 은 제출 파일 의 성공 여부,작업 완료,취소,업로드 정지 등 을 모두 제어 할 수 있 습 니 다.그들의 도움말 문서 도 비교적 완벽 하 게 작성 되 었 습 니 다.그러나 각 버 전의 방법 매개 변 수 는 완전히 다 르 지만 컨트롤 은 좋 은 컨트롤 입 니 다.
컨트롤 의 사용 은 먼저 필요 한 스 크 립 트 라 이브 러 리 를 추가 해 야 합 니 다.이 컨트롤 은 Jquery 의 기능 을 이용 하기 때문에 Jquery 스 크 립 트 파일 을 사용 해 야 합 니 다.다음 과 같 습 니 다

    <script src="https://www.jb51.net/JQuery/jquery-1.8.0.min.js" type="text/javascript"></script>
    <script src="https://www.jb51.net/JQueryTools/uploadify/jquery.uploadify-3.1.min.js" type="text/javascript"></script>
    <link href="https://www.jb51.net/JQueryTools/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
컨트롤 의 일부 인자 와 해당 하 는 처리 사건 을 설정 합 니 다.다음 과 같 습 니 다

<script language="javascript" type="text/javascript">
        $(function () {
            var guid = '<%=Request["guid"] %>';
            var type = '<%=Request["type"] %>';
            if (guid == null || guid == "") {
                guid = newGuid();
            }
            if (type != null) {
                type = type + '/';
            }

            $('#file_upload').uploadify({
                'swf': 'uploadify.swf',                        //FLash
                'buttonText': '   ',                        //
                'uploader': 'uploadhandler.ashx?guid=' + guid, // ASHX
                'formData' : { 'folder' : 'picture' },         //
                'queueID': 'fileQueue',                        // ID
                'queueSizeLimit': 10,                           // , 999
                'auto': false,                                 // , true
                'multi': true,                                 // , true
                'removeCompleted': true,                       // , true
                'fileSizeLimit': '10MB',                       // ,0 , KB,MB,GB
                'fileTypeDesc': 'Image Files',                 //
                'fileTypeExts': '*.gif; *.jpg; *.png; *.bmp',  //
                'onQueueComplete': function (event, data) {    //
                    //ShowUpFiles(guid, type, show_div);
                    alert(" !");
                },
                'onUploadError': function (event, queueId, fileObj, errorObj) {
                    alert(errorObj.type + ":" + errorObj.info);
                }
            });
        });

        function newGuid() {
            var guid = "";
            for (var i = 1; i <= 32; i++){
              var n = Math.floor(Math.random()*16.0).toString(16);
              guid +=   n;
              if((i==8)||(i==12)||(i==16)||(i==20))
                guid += "-";
            }
            return guid;
        }
    </script>

다시 한 번 말씀 드 리 지만 이 컨트롤 은 인터넷 의 다른 설명 을 참고 하지 마 십시오.그렇지 않 으 면 매개 변수 와 용법 이 정확 하지 않 을 수 있 습 니 다.반드시 해당 버 전의 설명(본 편 은 3.1.1)을 찾 아야 합 니 다.이 버 전의 온라인 문 서 를 참고 하 는 것 이 좋 습 니 다.
위의 매개 변 수 는 제 가 기본적으로 주석 을 달 았 고 중요 하지 않 은 매개 변수 도 있 습 니 다.여기 열거 되 지 않 았 으 니 온라인 문 서 를 참고 하 셔 야 합 니 다.
언급 할 만 한 것 은 이 버 전 은 Flash 안의 문 자 를 수정 할 수 있 습 니 다.아주 좋 습 니 다.예전 의 기본 Browse 의 영 어 를 싫어 합 니 다.예전 에 그림 을 대체 하여 문 자 를 수정 할 수 있 었 지만 잘 사용 되 지 않 았 습 니 다.이것 은 직접 문 자 를 수정 하 는 것 이 매우 좋다.
주의해 야 할 것 은 uploader 인자 입 니 다.이것 은 우리 ashx 의 배경 처리 프로그램 입 니 다.바로 컨트롤 이 파일 을 제출 하여 그 페이지 에 저장 처리 하고 데이터 베이스 기록 을 추가 하 는 등 작업 입 니 다.

페이지 코드 사용 은 매우 간단 합 니 다.다음 과 같 습 니 다

<body style="margin-left:10px; margin-top:10px">
    <form id="form1" runat="server"  enctype="multipart/form-data">
    <div id="fileQueue" class="fileQueue"></div>

    <div>
    <input type="file" name="file_upload" id="file_upload" />
        <p>
            <input type="button" class="shortbutton" id="btnUpload" onclick="javascript:$('#file_upload').uploadify('upload','*')" value=" " />
            &nbsp;&nbsp;&nbsp;&nbsp;
            <input type="button" class="shortbutton" id="btnCancelUpload" onclick="javascript:$('#file_upload').uploadify('cancel')" value=" " />
        </p>
        <div id="div_show_files"></div>
    </div>
    </form>
</body>

관건 은 배경 에 파일 을 업로드 하 는 저장 작업 입 니 다.asp.net 은 보통 ashx 처리 페이지 로 처리 합 니 다

/// <summary>
    ///
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class UploadHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";

            try
            {
                string guid = context.Request.QueryString["guid"];
                string folder = context.Request["folder"];
                //LogTextHelper.Info(folder);

                HttpPostedFile file = context.Request.Files["Filedata"];
                if (file != null)
                {                   
                    string oldFileName = file.FileName;//                    
                    int size = file.ContentLength;//

                    string extenstion = oldFileName.Substring(oldFileName.LastIndexOf(".") + 1);//                    
                    string newFileName = GetNewFileName(oldFileName);//
                    //LogTextHelper.Info(newFileName);

                    #region
                    //FileServerManage fsw = new FileServerManage();
                    //string uploadFilePath = "/" + newFileName;
                    //if (!string.IsNullOrEmpty(folder))
                    //{
                    //    uploadFilePath = string.Format("/{0}/{1}", folder, newFileName);
                    //}
                    //bool uploaded = fsw.UploadFile(file.InputStream, "/" + folder + "/" + newFileName);
                    #endregion

                    #region

                    AppConfig config = new AppConfig();
                    string uploadFiles = config.AppConfigGet("uploadFiles");
                    if (string.IsNullOrEmpty(uploadFiles))
                    {
                        uploadFiles = "uploadFiles";
                    }
                    if (!string.IsNullOrEmpty(folder))
                    {
                        uploadFiles = Path.Combine(uploadFiles, folder);
                    }

                    string uploadPath = Path.Combine(HttpContext.Current.Server.MapPath("/"), uploadFiles);
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }
                    string newFilePath = Path.Combine(uploadPath, newFileName);
                    LogTextHelper.Info(newFilePath);
                    file.SaveAs(newFilePath);
                    bool uploaded = File.Exists(newFilePath);

                    #endregion

                    if (uploaded)
                    {
                        #region ,
                        //AttachmentInfo attachmentInfo = new AttachmentInfo();
                        //attachmentInfo.EditorTime = DateTime.Now;
                        //attachmentInfo.FileExtend = extenstion;
                        //attachmentInfo.FileName = folader + "/" + newFileName;
                        //attachmentInfo.OldFileName = oldFileName;
                        //attachmentInfo.Size = size;
                        //attachmentInfo.Guid = guid;
                        //BLLFactory<Attachment>.Instance.Insert(attachmentInfo);
                        #endregion
                    }
                }
                else
                {
                    LogTextHelper.Error(" ");
                }
            }
            catch (Exception ex)
            {
                LogTextHelper.Error(" ", ex);
                throw;
            }
        }

        /// <summary>
        /// :aa.jpg aa(20090504).jpg
        /// </summary>
        /// <param name="fileName"> [aa.jpg]</param>
        /// <returns> </returns>
        public static string GetNewFileName(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return string.Empty;

            //
            string extenstion = fileName.Substring(fileName.LastIndexOf(".") + 1);
            string name = fileName.Substring(0, fileName.LastIndexOf(".")) + "(" + DateTime.Now.ToFileTime() + ")";
            string newFileName = name + "." + extenstion;
            return newFileName;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }


좋은 웹페이지 즐겨찾기