javascript - How to post and submit the image and string to the server when uploading the image?
仅有的幸福
仅有的幸福 2017-06-28 09:25:01
0
3
901

When uploading pictures, you need to provide the user's login token and the pictures to be uploaded. But how can two different data types be posted to the server together?

         mui.init();
         function fsubmit(){  
            var data = new FormData(mui('#uploadForm')[0]); //获取图片
            $.ajax({  
                url: 'http://192.168.1.8/api/user-center/avatar',  
                type: 'POST',  
                data: {
                    key:localStorage.getItem('key'), //获取本地的登录令牌
                    avatar:data        //图片
                }, 
                cache: false,  
                processData: false,  
                contentType: false ,
                success:function(data){
                    console.log(data.datas.testURL);
                },
                error:function(xhr,type,error){
                    console.log(xhr.status+xhr.responseText);
                    //一直返回401,没有权限
                }
            });
            return false;  
        }
仅有的幸福
仅有的幸福

reply all(3)
女神的闺蜜爱上我

Change the data type of post to formdata, and then load the object in formdata. The following is an example:

    var fd = new FormData();
    var file_data = $('input[type="file"]')[0].files; // for multiple files
    for(var i = 0;i<file_data.length;i++){
        fd.append("file_"+i, file_data[i]);
    }
    var other_data = $('form').serializeArray();
    $.each(other_data,function(key,input){
        fd.append(input.name,input.value);
    });
    $.ajax({
        url: 'caiyongji.com/segmentfault',
        data: fd,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(data){
            console.log(data);
        }
    });
洪涛

You have already created the new FormData, so don’t save objects by yourself. Just use the new one...

mui.init();
function fsubmit() {
    var fData = new FormData(); //这里用空的就行,后边再append
    fData.append('file', mui('#uploadForm')[0], '不知道你文件名是啥你自己去整下.jpg');
    fData.append('key', localStorage.getItem('key')); //获取本地的登录令牌
    $.ajax({
        url: 'http://192.168.1.8/api/user-center/avatar',
        type: 'POST',
        data: fData,
        processData: false,
        contentType: false,
        success: function (data) {
            console.log(data.datas.testURL);
        },
        error: function (xhr, type, error) {
            console.log(xhr.status + xhr.responseText);
        }
    });
    return false;
}

Then the backend is slightly adjusted to be able to receive FormData.

女神的闺蜜爱上我

Thanks for the invitation:

Token can be placed in headers, and the backend checks the token separately, while this interface only processes images

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template