PHP + JS:如何做HTML内容类型Multipart(通过JS)的Fileuploads? [英] PHP+JS: How to do Fileuploads in HTML Form as Content-Type Multipart (via JS)?

查看:117
本文介绍了PHP + JS:如何做HTML内容类型Multipart(通过JS)的Fileuploads?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


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

  2. 此外还有一个通过canvas
    对象(getImageData())的Javascript读取的图像。




  3. 问题: 如何注入此图像数据到HTML表单中,以便它以Content-Type:multipart / form-data的形式上传,并且可以通过现有的PHP框架数据抽取逻辑进行处理?

    一个< input type =file通过一个POST请求中的CHrome捕获上传=>它应该看起来像这样

      ------ WebKitFormBoundaryBBAQ5B4Ax1NgxFmD 
    Content-Disposition:form-data; NAME = 图像; filename =fooimage.png
    Content-Type:image / png

    问题:
    我知道如何在单独的请求中通过ajax上传它(通过ajax,与表单分离)。我知道如何将其上传为base64 Data,并在表单中手动处理它。


    但我不知道如何将图像数据沿着退出的表单发送,以便它查找PHP Serverside脚本与通过< input type =file...



    原因:Symphony(FileUpload Object)检查文件是否上传通过POST表单,并失败,如果我manulally instanciate与数据的对象。

    所以最好的解决方案是(关于很多其他的东西,如测试,避免不必要的逻辑),如果数据将作为常规表单上传进行传递。如何做到这一点?



    谢谢!

    解决方案

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



    这个blob将被服务器视为一个文件。



    不幸的是,所有浏览器仍然不支持原生 画布。 toBlob() 方法,甚至值得所有实现不一样。

    所有主流浏览器现在都支持toBlob方法,您可以在 mdn上的老式浏览器上的polyfill

    code> //创建和发送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);

    },类型,质量);
    };

    //如何使用//

    var form = document.querySelector('form'),//构造FormData的表单可以为null或undefined只发送图像
    url ='http://example.com/upload.php',//必填,我们将发送它的网址
    canvas = document.querySelector('canvas' ),//需要,画布发送
    filename =(new Date())。getTime()+'.jpg',//必需,文件名
    type ='image / jpeg', //可选,编码画布的算法。如果省略,则默认为'image / png'
    quality = .5,//可选,如果类型设置为jpeg,则设置编码质量的参数0-1
    callback = function(e ){console.log(this.response);}; //可选,xhr完成后的回调

    send(表单,网址,画布,文件名,类型,质量,回调);

    PHP端会是:

    <$ p如果(isset($ _FILES [file])){
    $ dir ='some / dir /'; $ p $
    $ blob = file_get_contents($ _ FILES [file] ['tmp_name']);
    file_put_contents($ dir。$ _ FILES [file] [name],$ blob);
    }


    1. Having an HTML Form that is submittet via POST (user clicking the submit button).

    2. Furthermore having an image that is read via Javascript of a canvas object (getImageData()).

    Question:

    How to "inject" this image data into the HTML Form, so that it gets uploaded as Content-Type:multipart/form-data and can be processed via the existing PHP Frameworks Data Extraction Logic?

    Example from a <input type="file" upload captured with CHrome in a POST request => it should look like this

    ------WebKitFormBoundaryBBAQ5B4Ax1NgxFmD
    Content-Disposition: form-data; name="images"; filename="fooimage.png"
    Content-Type: image/png
    

    Problem: I know how to uploed it in a seperate request (via ajax, seperate from the form). I know how to upload it as base64 Data an process it manually in the form.

    But I do not know how to send the Image Data along the exiting Form so that it looks for the PHP Serverside Scripts exactly the same as an image that is send via <input type="file"...

    Reason: Symphony (FileUpload Object) checks if a file is uploaded via the POST Form and fails if I manulally instanciate the object with the data.
    So the best solution would be (in regards to a lot of other things, like testing, avoiding unnecessary logik), if the data would be passed the same as a regular form upload. How to do this?

    Thanks!

    解决方案

    You can use a FormData object to get the values of your form, and then append a blob version of your canvas into the FormData.

    This blob will be seen as a file by the server.

    Unfortunately, all browsers still don't support the native canvas.toBlob() method, and even worth, all implementations are not the same.
    All major browsers now support the toBlob method, and you can find a polyfill on mdn for older browsers.

    // 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 side would then be :

    if ( isset( $_FILES["file"] ) ){
        $dir = 'some/dir/';
        $blob = file_get_contents($_FILES["file"]['tmp_name']);
        file_put_contents($dir.$_FILES["file"]["name"], $blob);
        }
    

    这篇关于PHP + JS:如何做HTML内容类型Multipart(通过JS)的Fileuploads?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆