为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

幕布斯7119047 2019-11-04 14:02:03
具有通过POST提交的HTML表单(用户单击“提交”按钮)。此外,还具有通过画布对象的Javascript(getImageData())读取的图像。题:如何将该图像数据“注入”到HTML表单中,以便将其作为Content-Type:multipart / form-data上传并可以通过现有的PHP Frameworks数据提取逻辑进行处理?从<input type="file"CHrome在POST请求中捕获的上载示例=>它应如下所示------WebKitFormBoundaryBBAQ5B4Ax1NgxFmDContent-Disposition: form-data; name="images"; filename="fooimage.png"Content-Type: image/png问题: 我知道如何在单独的请求中提出要求(通过ajax,与表格分开)。我知道如何将它作为base64数据上载到表单中的手动处理过程。但是我不知道如何沿着现有的表单发送图像数据,以便它查找与通过发送的图像完全相同的PHP服务器端脚本。 <input type="file"...原因:Symphony(FileUpload对象)检查文件是否通过POST表单上传,如果我手动使用数据实例化对象,则失败。因此,最好的解决方案是(关于很多其他事情,例如测试,避免不必要的logik),如果数据将以与常规表单上载相同的方式传递。这个怎么做?谢谢!
查看完整描述

1 回答

?
ibeautiful

TA贡献1993条经验 获得超5个赞

您可以使用FormData对象获取表单的值,然后将画布的Blob版本附加到FormData中。


该斑点将被服务器视为文件。


不幸的是,所有浏览器仍然不支持本机canvas.toBlob()方法,甚至值得,所有实现都不相同。

现在,所有主要的浏览器都支持toBlob方法,并且您可以在mdn上为较旧的浏览器找到一个 polyfill。


// the function to create and send our FormData

var send = function(form, url, canvas, filename, type, quality, callback) {


  canvas.toBlob(function(blob){

    var formData = form ? new FormData(form) : new FormData();

    formData.append('file', blob, filename);


    var xhr = new XMLHttpRequest();

    xhr.onload = callback;

    xhr.open('POST', url);

    xhr.send(formData);


    }, type, quality);

};


// How to use it //


var form = document.querySelector('form'),   // the form to construct the FormData, can be null or undefined to send only the image

  url = 'http://example.com/upload.php',     // required, the url where we'll send it

  canvas = document.querySelector('canvas'), // required, the canvas to send

  filename = (new Date()).getTime() + '.jpg',// required, a filename

  type = 'image/jpeg',                       // optional, the algorithm to encode the canvas. If omitted defaults to 'image/png'

  quality = .5,                              // optional, if the type is set to jpeg, 0-1 parameter that sets the quality of the encoding

  callback = function(e) {console.log(this.response);}; // optional, a callback once the xhr finished


send(form, url, canvas, filename, type, quality, callback);

PHP方面将是:


if ( isset( $_FILES["file"] ) ){

    $dir = 'some/dir/';

    $blob = file_get_contents($_FILES["file"]['tmp_name']);

    file_put_contents($dir.$_FILES["file"]["name"], $blob);

    }


查看完整回答
反对 回复 2019-11-04
  • 1 回答
  • 0 关注
  • 578 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信