input file 文件上传

1   <a href="javascript:;" class="file"> <span>选择文件</span>
2                                     <input type="file" placeholder="" id="share-propagateUrl" size="1"
3                                            onchange="verificationPicFile(this,'showShareImg')">
4                                     <span id="showFileName" class="showFileName"></span>
5                                 </a>
/*分享图片*/
function verificationPicFile(file,img,bg) {
    var fileTypes = [".jpg", ".png",".jpeg"];
    var fileSize = 0;
    var fileMaxSize = 1024;//1M
    var filePath = file.value;
    var id = file.id;
    //当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false
    if (filePath) {
        var isNext = false;
        var fileEnd = filePath.substring(filePath.indexOf("."));
        for (var i = 0; i < fileTypes.length; i++) {
            if (fileTypes[i] == fileEnd) {
                isNext = true;
                break;
            }
        }
        if (!isNext) {
            parent.layer.msg("只接受"+fileTypes+"类型图片!", {icon: 2});
            file.value = "";
            return false;
        }

        var arr = filePath.split('\\');
        var fileName = arr[arr.length - 1];
        // $(".showFileName").html(fileName);

        fileSize = file.files[0].size;
        var size = fileSize / 1024;
        if (size > fileMaxSize) {
            parent.layer.msg("文件大小不能大于1M!", {icon: 2});
            file.value = "";
            return false;
        } else if (size <= 0) {
            parent.layer.msg("文件大小不能为0M!", {icon: 2});
            file.value = "";
            return false;
        }
    } else {
        return false;
    }
    getShareFile(id,img,bg);
};

function getShareFile(id,img,bg) {
    showLayerLoading();
    var formData = new FormData();
    formData.append("file_data", $("#" + id).get(0).files[0]);

    $.ajax({
        url: "后端接口",
        type: "post",
        enctype: 'multipart/form-data',
        data: formData,
        async: false,
        processData: false,
        contentType: false,
        success: function (msg) {
            propagateUrl = msg.data;
            // $(".showShareImg").attr("src", getMallUrl(msg.data));
            closeLayerLoading();
        },
        error: function (e) {
            console.log(JSON.stringify(e));
        }
    });
};
.file {
  position: relative;
  display: inline-block;
  background: #D0EEFF;
  border: 1px solid #99D3F5;
  border-radius: 4px;
  padding: 4px 12px;
  overflow: hidden;
  color: #1E88C7;
  text-decoration: none;
  text-indent: 0;
  line-height: 20px;
}
.file input {
  position: absolute;
  font-size: 100px;
  right: 0;
  top: 0;
  opacity: 0;
}
.file:hover {
  background: #AADFFD;
  border-color: #78C3F3;
  color: #004974;
  text-decoration: none;
}

 

posted @ 2020-05-06 11:27  leeSmile  阅读(894)  评论(0编辑  收藏  举报