如何使用jQuery File Upload上传后获取图像尺寸?

时间:2014-11-24 20:30:59

标签: javascript php jquery jquery-file-upload

当我尝试通过jQuery文件上传上传文件时,我正在接受以下回复。

It returns "false"

是否可以将图像尺寸添加到width: 300pxheight: 400px这样的结果中?我尝试编辑UploadHandler.php以满足这种需求,但我无法成功。 set_additional_file_properties中有一个名为UploadHandler.php的函数。我试图在函数中添加一个自定义变量,但它失败了,因为我认为在文件上传过程之前调用了这个函数。它甚至找不到要获取尺寸的文件。我不知道为什么我可能正在寻找文件的错误一面。

protected function set_additional_file_properties($file) {
    $file->dimensions = file_exists($file->url);
    $file->deleteUrl = $this->options['script_url']
        .$this->get_query_separator($this->options['script_url'])
        .$this->get_singular_param_name()
        .'='.rawurlencode($file->name);
    $file->deleteType = $this->options['delete_type'];
    if ($file->deleteType !== 'DELETE') {
        $file->deleteUrl .= '&_method=DELETE';
    }
    if ($this->options['access_control_allow_credentials']) {
        $file->deleteWithCredentials = true;
    }
}

解决方案

protected function set_additional_file_properties($file) {
    $a = getimagesize(realpath(dirname($file->url))."/".$file->name);
    $width = $a[0];
    $height = $a[1];
    if ($a) {
        $file->width = $width;
        $file->height = $height;
    }
    ...
}

2 个答案:

答案 0 :(得分:1)

如果我遇到了您的问题(您希望在服务器端向图像添加宽度和高度信息),那么这应该会有所帮助:

http://php.net/manual/function.getimagesize.php

  

返回最多包含7个元素的数组。并非所有图像类型都包含通道和位元素。   索引0和1分别包含图像的宽度和高度。

=>和getimagesize($文件)

答案 1 :(得分:0)

只需更改UploadHandler.php函数中的set_additional_file_properties($file)文件,即可:

protected function set_additional_file_properties($file) {
    $filesize = getimagesize("files/".$file->name); //'files' folder is default folder to upload
    $width = $filesize[0];
    $height = $filesize[1];
    if ($filesize) {
        $file->width = $width;
        $file->height = $height;
    }
    $file->deleteUrl = $this->options['script_url']
        .$this->get_query_separator($this->options['script_url'])
        .$this->get_singular_param_name()
        .'='.rawurlencode($file->name);
    $file->deleteType = $this->options['delete_type'];
    if ($file->deleteType !== 'DELETE') {
        $file->deleteUrl .= '&_method=DELETE';
    }
    if ($this->options['access_control_allow_credentials']) {
        $file->deleteWithCredentials = true;
    }
}

刚刚添加了以下几行:

$filesize = getimagesize("files/".$file->name); //'files' folder is default folder to upload
$width = $filesize[0];
$height = $filesize[1];
if ($filesize) {
    $file->width = $width;
    $file->height = $height;
}