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 参数。
You can have the following methods:
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
$_FILES
to get all the files/images in one traversal.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?
You first
F12
innetwork
to see if there are any parameters in this request