dongtidai6519 2015-10-18 00:02
浏览 186

来自数据blob的文件扩展名

I have javascript code that detects when an image is pasted into a contenteditable field:

document.onpaste = function(event){
    var items=(event.clipboardData || event.originalEvent.clipboardData || event.dataTransfer).items;
    for(i in items){
        var item=items[i];
        if(item.kind==='file' && ~item.type.indexOf("image")){ //is file and is image
            event.preventDefault();
            var blob=item.getAsFile();
            console.log(item, blob);
            var data=new FormData();
            data.append('fname','imageFromClipboard'); //extension for file name??
            data.append('newImage',blob);
            sendImage(data); //just a $.POST request
        }
    }
}

And PHP code that receives the POST request for the image:

$image = $_FILES['newImage'];
$imageFileType = pathinfo($image["name"],PATHINFO_EXTENSION); // obviously doesn't work
$imageId = new ImageId();
$imageName = $imageId.".".$imageFileType;
// [... some checks on the file ...]
$targetFile = "../../images/uploads/{$imageName}";
if($imageOK && move_uploaded_file($image["tmp_name"],$targetFile)){ 
//[ do stuff ]

How do I get the file extension reliably from the blob? Should I do it with JS or PHP? Is it fine for all possible image file types to just split the MIME type ("image/png" for instance) at the slash and just use that as an extension?

  • 写回答

1条回答 默认 最新

  • dongyan8929 2015-10-18 00:26
    关注

    Splitting the mime type should be ok. Only problem mime_content_type function deprecated.

    mime_content_type — Detect MIME Content-type for a file (deprecated)

    You will have to use finfo_file instead.

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $ftype = finfo_file($finfo, $image["tmp_name"])
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料