javascript - 表單如何提交base64的格式的圖片?

來源:互聯網
上載者:User

後端是用PHP的$_FILES變數擷取提交的檔案。

正常的表單提交是這樣。

正常表單提交,enctype=multipart/form-data

我這裡的情況是,上傳的檔案,是來自外部的一串base64字串,這裡該如何轉變,才能實現類比表單提交,後台不需要更改代碼。

PS:
我嘗試把base64放在FormData對象裡面,但背景$_FILES變數依舊不能識別

function sendFormByBase64(){    var form = document.getElementById('form-2');    var formData = new FormData();    var base64 ='/* 這裡面是base64字串 */';    formData.append('file', base64);    var xhr = new XMLHttpRequest();    xhr.open('POST', form.action, true);    xhr.send(formData);}

PS2:再附抓包圖

base64的抓包

正常post提交表單檔案的抓包

回複內容:

後端是用PHP的$_FILES變數擷取提交的檔案。

正常的表單提交是這樣。

正常表單提交,enctype=multipart/form-data

我這裡的情況是,上傳的檔案,是來自外部的一串base64字串,這裡該如何轉變,才能實現類比表單提交,後台不需要更改代碼。

PS:
我嘗試把base64放在FormData對象裡面,但背景$_FILES變數依舊不能識別

function sendFormByBase64(){    var form = document.getElementById('form-2');    var formData = new FormData();    var base64 ='/* 這裡面是base64字串 */';    formData.append('file', base64);    var xhr = new XMLHttpRequest();    xhr.open('POST', form.action, true);    xhr.send(formData);}

PS2:再附抓包圖

base64的抓包

正常post提交表單檔案的抓包

你這個問題我剛剛遇到了,但我用tornado+ajax,希望對你有協助
base64的圖片資料,你直接用普通表單(xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded ");),當作字串傳後伺服器就可以了,但是因為一些特殊字元的表單資料很危險,所以要進行url編碼encodeURIComponent()

function sendimg(b64img){    var xhr = new XMLHttpRequest();    xhr.onreadystatechange = function () {        if (xhr.readyState == 4) {            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {                //            } else {                //            }        }    };    xhr.open("post", "/upload.php", true);    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded ");    xhr.send("img="+encodeURIComponent(shared.imageDataURL));}

伺服器接受到表單nameimg的資料即為url編碼後的base64資料,解碼後就是你要的
關於ajax和幕後處理的代碼可以看看我的小項目:)

Ps:木有看時間,題主在上半年提問的QAQ, 現在問題應該已經解決了~ o(∩∩)o...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.