本文介绍了PHP+JS:如何将 HTML 表单中的文件上传为 Content-Type Multipart(通过 JS)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 拥有一个通过 POST 提交的 HTML 表单(用户单击提交按钮).

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

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

Furthermore having an image that is read via Javascript of a canvasobject (getImageData()).


现在所有主流浏览器都支持 toBlob 方法,你可以找到 mdn 上的一个 polyfill,适用于旧版浏览器.


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 方面将是:

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 表单中的文件上传为 Content-Type Multipart(通过 JS)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:04
查看更多