如何通过数据uri将图像上传到通过javascript输入的文件?

时间:2018-11-23 20:35:51

标签: javascript file input data-uri

我有这行代码

<div class="user-post-image"> </div>
<input type="file" name="upload-image" id="upload-image" required />

我有这张图片

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAAAS1BMVEUAAAACCBEBBQsDCxYBBAkZTZoCCBAAAQIBAwcAAgUYSJAOLFgCCBASNmwVPn0KHz8RM2YVQIEHFSoYSZISOHAXRosdV6wbUqMdVqpe5uSXAAAAFnRSTlMAIStBF/w2Aw8I7aBNwNqBY6ln3IXGCM4jMgAABJhJREFUeF7tmuly5CAMhMNpwPcleP8nXRkmoXZTGbMaJv7jfoGvJVrCZfvjzbp169atW7duWSMZ49xeRtfTvK9uZb/ObiQXyN7X1Snllf5ofpFt2LTNu/OogAIANTW/ZSD1XB3oLFCb+RUDWPnulEIiIDYL/Mzs2xvPpnk9mg6ZnrVy+9YWWKQ7H3Lp/8oJ27y1dqc8hCdy09tCYPWGmfux9JzC94TApNZDeC5Q7VsMsGnH4gsEvpf1Q8CO3kMoNVA7BHJbfYBQKBjQwGX4+gbMtMejv8qA3lWA6wzIzXmAcJUBO62x/KsMsDlO3mUGRCz/MgN2i/jLDGD7EXCdAb17IPPV66t4cgR+vbvAbo6Uvnwdv2bA5PgRDWwvGTA5fkS5RdrmQn5wHRq4kB9WQTdgN58B5CHQ0hL5zfZ6/aBabiwN/zGpUMHAyExD4wsXahhYqFPI4v59WSt1COwc+RUySDSAAaggCC2jDYFeA9Qw4EdSBBpT4wBQ4Do0QJrAKvwAAy0Ccg915FuOBggN8JUaoBZmLGUFBAhV5ARhDzZNtQT4mXQCcq92AiNDAxc0IO9hygnY2YdaJ6AlwYBeQ6h4Av8/g4uqxA9DR2mAnGtF0Lc8GyhvQLUTCG4hzkBBcUU96jUjnUDBECpXwFcjpzTg/EkM/DD2BQkYBOEeaOx5BHy/LK5kBjllBszZGgTVd11bMChDR3kYs3I7MaDaTpc0wI+ctIb57OGEL0Rf2gCCAfE8g6oVmm+qegOygWkNZ3xRsqkGwaWlGNjcs7IOPitY1aCoDbCtesbvNJdTyQH01AaY1j/NP5clVwW4JTaAYqCHn6pKfFlyAL7VTFqKAfOjAfD9wTdxTZyPYFyC1QxkvhWu6EFIM2NpBmQPz/jxpqInkG7ADwvyjdmQf6qcwDoGMj8+q5ATSDcAkY9F8TUUqBcxgWQD6hs/uMQ3cyiZgCUmkGzg2yYEcOPBt82myiYgJpBuwP3DjxcQ8j9EWQDSAdANjKv/G/DgHwEomcCOH2apaqycdg//lBRDbWZfUP/Q5QkgGhCzh79LSkNV8trauyUHgGqAtx6+LcDC17aY1hwAagjYpiDz0wKyZa9tVZqWl3/FcnkAPvmm7CEopfVFA1KsX/y0AIoCACHycwDoIcgfKbGkxJ/UOd/V4KOs4a2CvxbAB189EPjkM1iiAfAPfkEAwA91+MlA52JNjwXQ2E2d8vulAj+HoPdHTWkBnAUgXRZdLT7KStb6OICJz9ez8t3YpWGp9lPm4h47DfknL00BFLY/8+sY0EMawBSAk/KP9nOZ+VXOYGsT//mHIzjwi0CrFfkoa5jWif/kCoID34+f5Wd+lTlgLA7gz1cQQHjgc/k1W4BCfvPTl0Okq6FdOiE0S+XXFZIRj9oUICwLUIhHej8iXtcvP1tIH868Dx6+FLz3QblE/8JnfnUTemz7wakvIbpvEd4h/qAX4ulZNFJ3yzi2D43jclQuIv0ovhhPHwauEdclPdiaRzriy+n0DjDOdVZkH50nFE90YKSU7FMSZSKcQCcJQdZakxTRteG3bt26devWrT+iVfLjHE+E5QAAAABJRU5ErkJggg==

,尽管我不想保存到我的PC上。当我实际上传此图片时,网页使用

更改了div元素的innerHTML。
<img src='data:image/png;base64....'> 

我上传的图片。所以我试图通过javascript来更改它(div),但是它不允许我继续前进。不幸的是,它需要在输入元素上获得某种值。如何通过“提供”到输入文件标签来将图像的数据uri“值”上传到输入文件中?

1 个答案:

答案 0 :(得分:0)

通过阅读模糊的答案,我认为您具有一个将输入文件自动转换为DIV的功能。

因此,这可能是Convert Data URI to File then append to FormData的副本。从那里,您可以通过AJAX函数将文件发送到服务器或其他东西。

var img = document.getElementsByClassName("user-post-image")[0]; //Get img data
var blob = dataURItoBlob(img); //Converts to blob using link above
var form = new FormData();
form.append("image", blob);
ajax.send(form); //The possible data sent.

除此之外,您可能必须提供有关“继续前进”含义的更多信息。