js 上傳文件到 java 項目中

以下是上傳圖片文件的一個小工具


uploadFile={
    alert:function(msg){
        common.alert(msg);
    },
    loading:function(){
        loading();
    },
    closeLoading:function(){
        loaded();
    },
    getFileName:function (filePath) {
        if (filePath.indexOf("/")==-1){
            var pos=filePath.lastIndexOf("\\");
            return filePath.substring(pos+1);
        }else{
            var pos=filePath.lastIndexOf("/");
            return filePath.substring(pos+1);
        }
    },
    checkParam:function (initObj) {
        var fileId = initObj.fileId;
        var fileTypes = initObj.fileTypes;
        if (!fileId){
            console.error("fileId 不能爲空");
            uploadFile.alert("uploadFile.fileInit fileId 不能爲空")
            return false;
        }
        if (!fileTypes){
            console.error("fileTypes 不能爲空");
            uploadFile.alert("uploadFile.fileInit fileTypes 不能爲空")
            return false;
        }
    }
    ,
    fileInit:function (options) {


        var defaults = {
            serverFileId: "file_data",
            method:"post",
            width:"100%",
            height:"300px",
            uploadShowText:"+上傳文件",
            viewImgUrl:"",
            viewButton :"<button type=\"button\" class=\"kv-file-zoom btn btn-sm btn-kv btn-default btn-outline-secondary\" title=\"View Details\"><i class=\"glyphicon glyphicon-zoom-in\"></i></button>",
            log:false
        };

        var initObj = $.extend(defaults, options);
        if (initObj.log){
            console.log(initObj);
        }

        //回顯圖片
        if (initObj.viewImgUrl){
            initObj.uploadShowText = "<img src='"+initObj.viewImgUrl+"' style='width: 100%;height: 100%;' />"
        }

        uploadFile.checkParam(initObj);

        var fileId = initObj.fileId;
        var selectorFileId = "#"+fileId;
        //給fileId 隱藏基礎樣式
        $("#"+fileId).attr("style","position: absolute;left: 0;top: 0;opacity: 0;");

        var addDivId = fileId+"addDivId";
        var topDivId = fileId+"TopDivId";

        //刪除上一張回顯圖片
        if ($("#"+addDivId).length>0){
            $("#"+addDivId).remove();
        }

        var fileParent = $("#"+fileId).parent();
        //獲取input file html
        var fileHtml =$(fileParent).html();


        initObj.viewDivId = addDivId;

        if (initObj.height.indexOf("%")==0){
            var height = initObj.height.replaceAll("%","");
            var reHeight = (parseInt(height)/100)*8;
            initObj.innerHeight = reHeight+"%";
        }else if (initObj.height.indexOf("px")==0){
            var height = initObj.height.replaceAll("px","");
            var reHeight = (parseInt(height)/100)*8;
            initObj.innerHeight = reHeight+"px";
        }


        var topDivStyle ="width:"+initObj.width+";height:"+initObj.height+";border:1px solid #e5e6e7;border-radius: 2px;";
        var viewDivStyle = "line-height: 260px;text-align: center;"+"width:"+initObj.width+";height:99%;";

        var html="<div style=\""+topDivStyle+"\" id='"+topDivId+"'>" +
                    "<div id="+addDivId+" onclick='document.querySelector(\""+selectorFileId+"\").click()'  style=\""+viewDivStyle+"\"> "
                        +initObj.uploadShowText+
                    "</div>"
                    +fileHtml+
                 "</div>"

        if ($("#"+(topDivId+"Top")).length>0){
            $("#"+(topDivId+"Top")).html(html);
        }else{
            fileParent.attr("id",(topDivId+"Top"));
            fileParent.html(html);
        }

        $('#'+fileId).on('change', function(e) {
            e.stopPropagation;
            uploadFile.fileChange(this,initObj);
        });

    },
    fileChange:function (obj,initObj) {
        var filePath = $(obj).val();
        if (filePath==null || filePath==""){
            return false;
        }

        var file = document.getElementById(initObj.fileId).files[0];
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(result){
            initObj.localFile = result.target.result;
        }


        var fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
        if (initObj.log) {
            console.log(filePath);
            console.log(initObj.fileTypes);
            console.log(fileFormat);
        }
        if(initObj.fileTypes.indexOf(fileFormat)==-1) {
            if (initObj.log) {
                console.error('上傳錯誤,文件格式必須爲:' + initObj.fileTypes);
            }
            uploadFile.alert('上傳錯誤,文件格式必須爲:'+initObj.fileTypes);
            return;
        }else{
            uploadFile.uploadServer(initObj);
        }
        //防止文件不能重複上傳
        $('#'+initObj.fileId).val('');
    },
    uploadServer:function (initObj) {

        var fd = new FormData();
        fd.append(initObj.serverFileId, $("#"+initObj.fileId)[0].files[0]);
        if (initObj.formData){
            fd = initObj.formData;
        }

        $.ajax({
            url: initObj.url,
            type: initObj.method,
            data:fd,
            contentType:false,
            processData:false,//這個很有必要,不然不行
            dataType:"json",
            mimeType:"multipart/form-data",
            beforeSend: function () {
                uploadFile.loading();
            },
            success: function (data) {
                uploadFile.closeLoading();
                if (typeof initObj.callback == "function") {
                    initObj.callback(data,initObj);
                }
            },error: function (e){
                if (initObj.log) {
                    console.error(e);
                }
                uploadFile.closeLoading();
                uploadFile.alert("上傳文件失敗");
            }
        });
    },S4:function () {
        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    },guid:function () {
        return (uploadFile.S4()+uploadFile.S4()+uploadFile.S4()+uploadFile.S4()+uploadFile.S4()+uploadFile.S4()+uploadFile.S4()+uploadFile.S4());
    }
}

 使用方式如下 

 

 

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"> 
	<title>Bootstrap 實例 - 水平表單</title>
	<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">  
	<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
	<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<form class="form-horizontal" role="form">
	<div class="form-group">
		<label for="firstname" class="col-sm-2 control-label">名字</label>
		<div class="col-sm-10">
			<input type="text" class="form-control" id="firstname" 
				   placeholder="請輸入名字">
		</div>
	</div>
	<div class="form-group">
		<label for="lastname" class="col-sm-2 control-label">添加文件</label>
		<div class="col-sm-10">
			<input type="file"  id="addFile" />
		</div>
	</div>
	<div class="form-group">
		<label for="lastname" class="col-sm-2 control-label">回顯文件</label>
		<div class="col-sm-10">
			<input type="file"  id="editFile" />
		</div>
	</div>

</form>

</body>
	
	<script>
		
uploadFile={
    alert:function(msg){
        common.alert(msg);
    },
    loading:function(){
        loading();
    },
    closeLoading:function(){
        loaded();
    },
    getFileName:function (filePath) {
        if (filePath.indexOf("/")==-1){
            var pos=filePath.lastIndexOf("\\");
            return filePath.substring(pos+1);
        }else{
            var pos=filePath.lastIndexOf("/");
            return filePath.substring(pos+1);
        }
    },
    checkParam:function (initObj) {
        var fileId = initObj.fileId;
        var fileTypes = initObj.fileTypes;
        if (!fileId){
            console.error("fileId 不能爲空");
            uploadFile.alert("uploadFile.fileInit fileId 不能爲空")
            return false;
        }
        if (!fileTypes){
            console.error("fileTypes 不能爲空");
            uploadFile.alert("uploadFile.fileInit fileTypes 不能爲空")
            return false;
        }
    }
    ,
    fileInit:function (options) {


        var defaults = {
            serverFileId: "file_data",
            method:"post",
            width:"100%",
            height:"300px",
            uploadShowText:"+上傳文件",
            viewImgUrl:"",
            viewButton :"<button type=\"button\" class=\"kv-file-zoom btn btn-sm btn-kv btn-default btn-outline-secondary\" title=\"View Details\"><i class=\"glyphicon glyphicon-zoom-in\"></i></button>",
            log:false
        };

        var initObj = $.extend(defaults, options);
        if (initObj.log){
            console.log(initObj);
        }

        //回顯圖片
        if (initObj.viewImgUrl){
            initObj.uploadShowText = "<img src='"+initObj.viewImgUrl+"' style='width: 100%;height: 100%;' />"
        }

        uploadFile.checkParam(initObj);

        var fileId = initObj.fileId;
        var selectorFileId = "#"+fileId;
        //給fileId 隱藏基礎樣式
        $("#"+fileId).attr("style","position: absolute;left: 0;top: 0;opacity: 0;");

        var addDivId = fileId+"addDivId";
        var topDivId = fileId+"TopDivId";

        //刪除上一張回顯圖片
        if ($("#"+addDivId).length>0){
            $("#"+addDivId).remove();
        }

        var fileParent = $("#"+fileId).parent();
        //獲取input file html
        var fileHtml =$(fileParent).html();


        initObj.viewDivId = addDivId;

        if (initObj.height.indexOf("%")==0){
            var height = initObj.height.replaceAll("%","");
            var reHeight = (parseInt(height)/100)*8;
            initObj.innerHeight = reHeight+"%";
        }else if (initObj.height.indexOf("px")==0){
            var height = initObj.height.replaceAll("px","");
            var reHeight = (parseInt(height)/100)*8;
            initObj.innerHeight = reHeight+"px";
        }


        var topDivStyle ="width:"+initObj.width+";height:"+initObj.height+";border:1px solid #e5e6e7;border-radius: 2px;";
        var viewDivStyle = "line-height: 260px;text-align: center;"+"width:"+initObj.width+";height:99%;";

        var html="<div style=\""+topDivStyle+"\" id='"+topDivId+"'>" +
                    "<div id="+addDivId+" onclick='document.querySelector(\""+selectorFileId+"\").click()'  style=\""+viewDivStyle+"\"> "
                        +initObj.uploadShowText+
                    "</div>"
                    +fileHtml+
                 "</div>"

        if ($("#"+(topDivId+"Top")).length>0){
            $("#"+(topDivId+"Top")).html(html);
        }else{
            fileParent.attr("id",(topDivId+"Top"));
            fileParent.html(html);
        }

        $('#'+fileId).on('change', function(e) {
            e.stopPropagation;
            uploadFile.fileChange(this,initObj);
        });

    },
    fileChange:function (obj,initObj) {
        var filePath = $(obj).val();
        if (filePath==null || filePath==""){
            return false;
        }

        var file = document.getElementById(initObj.fileId).files[0];
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(result){
            initObj.localFile = result.target.result;
        }


        var fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
        if (initObj.log) {
            console.log(filePath);
            console.log(initObj.fileTypes);
            console.log(fileFormat);
        }
        if(initObj.fileTypes.indexOf(fileFormat)==-1) {
            if (initObj.log) {
                console.error('上傳錯誤,文件格式必須爲:' + initObj.fileTypes);
            }
            uploadFile.alert('上傳錯誤,文件格式必須爲:'+initObj.fileTypes);
            return;
        }else{
            uploadFile.uploadServer(initObj);
        }
        //防止文件不能重複上傳
        $('#'+initObj.fileId).val('');
    },
    uploadServer:function (initObj) {

        var fd = new FormData();
        fd.append(initObj.serverFileId, $("#"+initObj.fileId)[0].files[0]);
        if (initObj.formData){
            fd = initObj.formData;
        }

        $.ajax({
            url: initObj.url,
            type: initObj.method,
            data:fd,
            contentType:false,
            processData:false,//這個很有必要,不然不行
            dataType:"json",
            mimeType:"multipart/form-data",
            beforeSend: function () {
                uploadFile.loading();
            },
            success: function (data) {
                uploadFile.closeLoading();
                if (typeof initObj.callback == "function") {
                    initObj.callback(data,initObj);
                }
            },error: function (e){
                if (initObj.log) {
                    console.error(e);
                }
                uploadFile.closeLoading();
                uploadFile.alert("上傳文件失敗");
            }
        });
    },S4:function () {
        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    },guid:function () {
        return (uploadFile.S4()+uploadFile.S4()+uploadFile.S4()+uploadFile.S4()+uploadFile.S4()+uploadFile.S4()+uploadFile.S4()+uploadFile.S4());
    }
}
		initFile();
		//初始化一個輸入框
		function initFile(){
		  var options ={
				fileId:"addFile",
				fileTypes:".png,.jpeg,jpg",
				url:"url",
				serverFileId:"file_data",
				callback:callback
			}
    		uploadFile.fileInit(options);
		}

    function callback(data,option){
        var filePath= data.data;
        $("#"+option.viewDivId).html("<img src='"+filePath+"' style='width: 100%;height: 100%;' />");
        $("#addUrl").val(filePath);//要賦值的id
    }
		
		initViewFile('https://img6.bdstatic.com/img/image/pcindex/sunjunpchuazhoutu.JPG');
		//回顯一個輸入框
	function initViewFile(imgUrl){
		  var options ={
				fileId:"editFile",
				fileTypes:".png,.jpeg,jpg",
				url:"url",
				serverFileId:"file_data",
			    viewImgUrl:imgUrl,//回顯url
				callback:callback2
			}
    		uploadFile.fileInit(options);
		}
	function callback2(data,option){
        var filePath= data.data;
        $("#"+option.viewDivId).html("<img src='"+filePath+"' style='width: 100%;height: 100%;' />");
        $("#addUrl").val(filePath);//要賦值的id
    }
		
</script>
	
</html>

 

測試結果

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章