HTML5、formData移动浏览器上传图片

 该上传方法对于不支持html5的浏览器无法使用。主要针对移动浏览器。

1、html

<div class="upload_img">
    <div  class="file">
        <span class="plus">+</span>
        <span class="text">请拍照上传</span>
        <input  class="fileupload" type="file" name="fangchanzheng1" accept="image/*" capture="camera" />
    </div>
    <p class="info"> 房产证照片 </p>
</div>
  • type 是file 加上capture=”camera” 可以在移动端打开摄像头。

2、CSS

修改上传文件按钮的css


.info {
    text-align: center;
    height: 36px;
    line-height: 36px;
    color: #666666;
    font-size: 12px;
}
.file .plus {
    display: inline-block;
    width: 100%;
    font-size: 86px;
    text-align: center;
    line-height: 67px;

}
.file .text {
    position: absolute;
    display: block;
    bottom: 12px;
    width: 100%;
    text-align: center; 
    height: 20px;
    line-height: 20px;
}
.file {
    position: relative;
    display: inline-block;
    background: #F3F3F3;
    border:1px solid #DCDCDC;
    color: #999999;
    border-radius: 0;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
    font-size: 12px;
    letter-spacing: normal;
    width: 100%;
    height: 96px;
    overflow: hidden;
    text-align: center;
    line-height: 96px;
}

.file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
    width: 100%;
    height: 96px;
}

3、图片预览

  • 图片预览使用了插件 https://github.com/blueimp/JavaScript-Load-Image
  • 代码如下,给上传按钮绑定change事件,change后调用thumbnail方法,在方法内部,当图片加载完成后,创建图片dom等操作,展示预览的图片。由于要替换图片所以给上传文件的按钮设置一个属性zidingyiname,所以在替换图片的时候,通过该属性就可以区分这个按钮要替换图片,遍历filesList把重复了的zidingyiname的file给删除。
  • 在这个方法的最后,把file对象push进filesList中,姑且认为这个是要上传的图片的数组。
var filesList = [];
var thumbnail = function (e) {
        var $house_imgs = $(".house-img-upload").eq(0);
        var $IDcard_imgs = $(".IDcard-img-upload").eq(0);
        var This = $(this);
        loadImage(
            e.target.files[0],
            function (img) {
                var $width = $(".file").eq(0).width();
                var $heigth = '96'; 
                // 设置图片显示的方法,这个方法应该拿出来,太忙了,没时间。
                if ($width/$heigth > $(img).attr('width')/$(img).attr('height')) {
                    var ratio = $heigth/$(img).attr('height');
                    $(img).css({
                        width: ratio*$(img).attr('width')+'px',
                        height: $heigth+'px'
                    });
                } else if($width/$heigth < $(img).attr('width')/$(img).attr('height')){
                    var ratio = $width/$(img).attr('width');
                    $(img).css({
                        width: $width+'px',
                        height: ratio*$(img).attr('height')+'px'
                    })
                }else {
                    var ratio = $width/$(img).attr('width');
                    $(img).css({
                        width: $width+'px',
                        height: ratio*$(img).attr('height')+'px'
                    })
                }
                                                                                                    This.parent().find('.plus').remove().end().find('.text').remove().end().find('img').remove();
                This.before($(img));
                This.parent().parent().next().css('display','inline-block');
            }
        );
        e.target.files[0].zidingyiname = This.attr('name');
        for (var i=0,l=filesList.length;i<l;i++) {
            if (This.attr('name') == filesList[i].zidingyiname) {
                filesList.splice(i,1)
                break;
            }
        }
        filesList.push(e.target.files[0]);
    }

    $('.fileupload').bind('change',thumbnail);

4、图片上传

  • 通过html5进行图片的上传,var formData = new FormData();创建formData对象,然后将需要上传的参数append到formData对象中。将上文提到的filesLlist进行遍历append到formData中。
$("#submitOrder").on('click', function() {
        var userName = $("#userName").val().trim();
        var amount = $("#amount").val().trim();
        var zhouqiSelect = $("#zhouqiSelect").find('select').eq(0).val();
        // 从url中获取productId;
        var url  = window.location.href;
        var productId = url.split("#")[1];

        if (userName.length != 0 && userName.length<5 && amount.length != 0 &&$(".house-img-upload").eq(0).find("img").length != 0) {

            var $upload_loading = $("#upload_loading");

            $upload_loading.fadeIn();


            var formData = new FormData();
            for (var i=0,l=filesList.length;i<l;i++) {
                formData.append(filesList[i].zidingyiname,filesList[i]);
            }

            formData.append('name',userName);
            formData.append('amount',amount);
            formData.append('zhouqi',zhouqiSelect);
            formData.append('productId',productId);
            formData.append('userId',$.cookie('userId'));
            formData.append('sectionId',$.cookie('sectionId'));
            formData.append('token',$.cookie('token'));

            $.ajax({
                url: urlEndPoint,  //server script to process data
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false
            }).done(function(res) {
                $upload_loading.fadeOut();

                CommonFn.saveCookie({"tips":res.tips})

                var _url = './orderSuccess.html';

                CommonFn.turnPageByPlatform(_url);
            }).fail(function(res) {
                $upload_loading.fadeOut();
                formData = null;
                alert('上传失败,请重新上传!');
                 window.location.reload();
            });;
        } else{
            alert("信息填写不正确!");
        }
    });
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于多张图片的上传,可以使用form表单的方式,并设置input的multiple属性。具体代码如下所示: ```html <form action="http://192.168.171.144/api/xxx" method="post" enctype="multipart/form-data"> 内容content: <input name="content" type="text" /> 图片images: <input name="images" multiple="multiple" type="file" /> <input type="submit" value="提交" /> </form> ``` 通过以上代码,可以实现多张图片的上传功能。 另外,如果你使用的是微信小程序开发,则需要注意微信本身没有FormData对象,无法直接使用new FormData。但可以通过wx.request发送multipart/form-data请求来模拟FormData的效果。具体代码如下所示: ```javascript wx.request({ url: app.globalData.pubUrl + '/Upload/UploadFile', // 接口地址 method: 'post', header: { 'content-type': 'multipart/form-data; boundary=XXX', 'Authorization': app.globalData.token }, data: '\r\n--XXX' + '\r\nContent-Disposition: form-data; name="UploadId"' + '\r\n' + '\r\n' + UploadId + '\r\n--XXX' + '\r\nContent-Disposition: form-data; name="IsDelete"' + '\r\n' + '\r\n' + IsDelete + '\r\n--XXX--', success: function (res) { // 接口成功返回的处理逻辑 if (res.data.success == false) { wx.showToast({ title: res.data.msg, icon: 'none', duration: 2000 }) } } }) ``` 以上代码中,需要自行替换URL、请求参数和请求头部信息,其中UploadId和IsDelete为上传图片接口所需的参数值。 请注意,以上代码是针对微信小程序开发中的图片上传情况,如果你使用的是其他平台或开发框架,请参考对应文档进行处理。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [通过JS创建FormData实现上传多张图片](https://blog.csdn.net/weixin_43974265/article/details/122016416)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [小程序FormData格式传参(上传图片,删除图片)](https://blog.csdn.net/weixin_45683261/article/details/128305221)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值