How to upload file array using formData
PHP中文网
PHP中文网 2017-07-05 11:02:53
0
3
1556

Because input type=‘file’ click again will overwrite the previous fileList, so I first convert the selected file to base64 as a preview image, similar to this, you can add it multiple times

But how do I add multiple preview images to the formdata object when uploading? The background parameter is a MultipartFile[] files array.

Here’s what I did wrong:

function getImgFiles() { var imgFiles = []; var imgs = $('img'); $.each(imgs, function (i, item) { var blob = dataURItoBlob(item.src); imgFiles.push(new File([blob], item.id)); }); return imgFiles; } /** * base64->blob * @param dataURI * @returns {Blob} */ function dataURItoBlob(dataURI) { var byteString = atob(dataURI.split(',')[1]); var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; var ab = new ArrayBuffer(byteString.length); var ia = new Uint8Array(ab); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return new Blob([ab], {type: mimeString}); } var formData = new FormData($('form').get(0)); formData.append('files', getImgFiles()); //然后使用ajax上传,但是后台没有接受到 files 参数。
PHP中文网
PHP中文网

认证0级讲师

reply all (3)
迷茫

You can have the following methods:

$.each(getImgFiles(), function(i, file){ formData.append('files', file); });
$.each(getImgFiles(), function(i, file){ formData.append('files[]', file); });
$.each(getImgFiles(), function(i, file){ formData.append('files_' + i, file); });

You should be able to receive files in the background. The specific method to use depends on the language and framework used in your backend.

As far as PHP is concerned, I like the last one, you can use$_FILESto get all the files/images in one traversal.

    phpcn_u1582

    Every time you transfer a file out of base64, you also need to create a blob and append it to your formData structure.

    Also, I remember that input can support multiple selections, right?

      typecho

      You firstF12innetworkto see if there are any parameters in this request

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!