猿问

PHP + JS:如何以HTML形式将文件上传为Content-Type Multipart?

具有通过POST提交的HTML表单(用户单击“提交”按钮)。


此外,还具有通过画布对象的Javascript(getImageData())读取的图像。


题:


如何将该图像数据“注入”到HTML表单中,以便将其作为Content-Type:multipart / form-data上传并可以通过现有的PHP Frameworks数据提取逻辑进行处理?


从<input type="file"CHrome在POST请求中捕获的上载示例=>它应如下所示


------WebKitFormBoundaryBBAQ5B4Ax1NgxFmD

Content-Disposition: form-data; name="images"; filename="fooimage.png"

Content-Type: image/png

问题: 我知道如何在单独的请求中提出要求(通过ajax,与表格分开)。我知道如何将它作为base64数据上载到表单中的手动处理过程。


但是我不知道如何沿着现有的表单发送图像数据,以便它查找与通过发送的图像完全相同的PHP服务器端脚本。 <input type="file"...


原因:Symphony(FileUpload对象)检查文件是否通过POST表单上传,如果我手动使用数据实例化对象,则失败。

因此,最好的解决方案是(关于很多其他事情,例如测试,避免不必要的logik),如果数据将以与常规表单上载相同的方式传递。这个怎么做?


谢谢!


幕布斯7119047
浏览 579回答 1
1回答

ibeautiful

您可以使用FormData对象获取表单的值,然后将画布的Blob版本附加到FormData中。该斑点将被服务器视为文件。不幸的是,所有浏览器仍然不支持本机canvas.toBlob()方法,甚至值得,所有实现都不相同。现在,所有主要的浏览器都支持toBlob方法,并且您可以在mdn上为较旧的浏览器找到一个 polyfill。// the function to create and send our FormDatavar send = function(form, url, canvas, filename, type, quality, callback) {&nbsp; canvas.toBlob(function(blob){&nbsp; &nbsp; var formData = form ? new FormData(form) : new FormData();&nbsp; &nbsp; formData.append('file', blob, filename);&nbsp; &nbsp; var xhr = new XMLHttpRequest();&nbsp; &nbsp; xhr.onload = callback;&nbsp; &nbsp; xhr.open('POST', url);&nbsp; &nbsp; xhr.send(formData);&nbsp; &nbsp; }, type, quality);};// How to use it //var form = document.querySelector('form'),&nbsp; &nbsp;// the form to construct the FormData, can be null or undefined to send only the image&nbsp; url = 'http://example.com/upload.php',&nbsp; &nbsp; &nbsp;// required, the url where we'll send it&nbsp; canvas = document.querySelector('canvas'), // required, the canvas to send&nbsp; filename = (new Date()).getTime() + '.jpg',// required, a filename&nbsp; type = 'image/jpeg',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// optional, the algorithm to encode the canvas. If omitted defaults to 'image/png'&nbsp; quality = .5,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // optional, if the type is set to jpeg, 0-1 parameter that sets the quality of the encoding&nbsp; callback = function(e) {console.log(this.response);}; // optional, a callback once the xhr finishedsend(form, url, canvas, filename, type, quality, callback);PHP方面将是:if ( isset( $_FILES["file"] ) ){&nbsp; &nbsp; $dir = 'some/dir/';&nbsp; &nbsp; $blob = file_get_contents($_FILES["file"]['tmp_name']);&nbsp; &nbsp; file_put_contents($dir.$_FILES["file"]["name"], $blob);&nbsp; &nbsp; }
随时随地看视频慕课网APP
我要回答