Home > Backend Development > PHP Tutorial > thinkphp (php) + Ajax upload pictures

thinkphp (php) + Ajax upload pictures

WBOY
Release: 2016-08-08 09:23:32
Original
1278 people have browsed it

External plug-ins used:

  • jquery.form.js (form submission): http://malsup.com/jquery/form/#download

  • jquery.json.min.js (parse json data ): http://www.oschina.net/p/jquery-json

Form code part:

<code><form tag=<span>"img_file_upload"</span> id=<span>"file_upload"</span> name=<span>"file_upload"</span><span>method</span>=<span>"post"</span> action=<span>"<{:U('File/fileUpload')}>" enctype=<span>"multipart/form-data"</span>>
    <input <span><span>type</span>=</span><span>"file"</span> id=<span>"img"</span> name=<span>"file"</span>>
    <input <span><span>type</span>=</span><span>"hidden"</span> name=<span>"member_id"</span><span>value</span>=<span>"<{:$_SESSION[C('USER_AUTH_KEY')]}>"/>
    <input <span><span>type</span>=</span><span>"button"</span><span>value</span>=<span>"上传"</span> >"submitImgForm()"</span>/>
</form>

<img tag=<span>"show_photo_upload_img"</span> src=<span>""</span> alt=<span>""</span>/></code>
Copy after login

js code:

<code><span><<span>script</span>></span><span><span><span>function</span><span>submitImgForm</span><span>()</span>{</span><span>if</span> ($(<span>"#img"</span>).val() == <span>""</span>) {
            alert(<span>"请选择一个图片文件,再点击上传。"</span>);
            <span>return</span>;
        }
        <span>var</span> file_form = $(<span>"[tag='img_file_upload']"</span>);
        <span>var</span> show_img = $(<span>"[tag='show_photo_upload_img']"</span>);
        <span>var</span> options = {
            type : <span>'post'</span>,
            url : <span>"<{:U('File/fileUpload')}>"</span>,
            dataType: <span>'text'</span>,
            contentType: <span>"application/json; charset=utf-8"</span>,
            beforeSubmit:<span><span>function</span><span>()</span>{</span>
              alert(<span>'正在上传'</span>);
            },
            success:<span><span>function</span><span>(data)</span> {</span><span>var</span> json_obj = <span>JSON</span>.parse(data);

                show_img.attr(<span>'src'</span>,json_obj.img_path);
                alert(json_obj.error);
            },
            error:<span><span>function</span><span>(XmlHttpRequest, textStatus, errorThrown)</span>{</span>
                alert(textStatus);
                alert(errorThrown);
            }
        };

        file_form.ajaxSubmit(options);
    }
</span><span></<span>script</span>></span></code>
Copy after login

Backend php part:

<code><span><span>function</span><span>fileUpload</span><span>()</span>{</span><span>$config</span> = C(<span>'FILE_UPLOAD_CONFIG'</span>);
        <span>//附带的信息</span><span>$request_data</span> = I(<span>'post.'</span>);
<span>//        show_bug($request_data);</span><span>$member_id</span> = <span>$request_data</span>[<span>'member_id'</span>];
        <span>if</span>(<span>empty</span>(<span>$the_file_usage</span>)){
            <span>$the_file_usage</span> = <span>$file_usage</span>[<span>'DOWNLOAD'</span>];
        }

<span>//        show_bug_with_exit($file_name);</span><span>$file_info</span>[<span>'member_id'</span>] = <span>$member_id</span>;
        <span>$file_info</span>[<span>'created_time'</span>] = time();

            <span>// 上传文件</span><span>//实例化上传类,传入上面的配置数组</span><span>$uploader</span> = <span>new</span> Upload(<span>$config</span>, <span>'Local'</span>);
<span>//            $uploader->saveName = $file_uuid;</span><span>$info</span> = <span>$uploader</span>->upload(<span>$_FILES</span>);
<span>//        show_bug_with_exit($info);</span><span>//这里判断是否上传成功</span><span>if</span> (<span>$info</span>) {
                <span>//// 上传成功 获取上传文件信息</span><span>foreach</span> (<span>$info</span><span>as</span> &<span>$file</span>) {
                    <span>//拼接出上传目录</span><span>$file</span>[<span>'rootpath'</span>] = __ROOT__ . ltrim(<span>$config</span>[<span>'rootPath'</span>], <span>"."</span>);
                    <span>//拼接出文件相对路径</span><span>$file</span>[<span>'filepath'</span>] = <span>$file</span>[<span>'rootpath'</span>] . <span>$file</span>[<span>'savepath'</span>] . <span>$file</span>[<span>'savename'</span>];
                }
                <span>//这里可以输出一下结果,相对路径的键名是$info['upload']['filepath']</span><span>$filepath</span> = <span>$file</span>[<span>'filepath'</span>];
<span>//                show_bug_with_exit($filepath);</span><span>$file_info</span>[<span>'file_path'</span>] = <span>$filepath</span>;


                <span>$save_file_in_DB</span> = <span>$this</span>->saveFileInfoIntoDB(<span>$file_info</span>);
                <span>//如果文件数据往数据库中存储失败,则删除文件</span><span>if</span>(!<span>$save_file_in_DB</span>){
                    unlink(<span>$filepath</span>);
                    <span>$return_data</span>[<span>'error'</span>] = <span>'文件上传失败,请重试'</span>;
                    <span>echo</span> json_encode(<span>$return_data</span>);
                }

                <span>$return_data</span>[<span>'error'</span>] = <span>'文件上传成功'</span>;
                <span>$return_data</span>[<span>'img_path'</span>] = <span>$filepath</span>;
                <span>$return_data</span>[<span>'img_id'</span>] = <span>$save_file_in_DB</span>;
                jsonReturn(<span>$return_data</span>);
            } <span>else</span> {
                <span>//输出错误信息</span><span>$error_msg</span> = <span>$uploader</span>->getError();
                <span>$return_data</span>[<span>'error'</span>] = <span>$error_msg</span>;
                jsonReturn(<span>$return_data</span>);
            }
    }


    <span><span>function</span><span>saveFileInfoIntoDB</span><span>(<span>$file_info</span>)</span>{</span><span>$file</span> = M(<span>'File'</span>);
        <span>$rs_u_file</span> = <span>$file</span>->add(<span>$file_info</span>);
        <span>$file_id</span> = <span>$file</span>->getLastInsID();
        <span>if</span>(!<span>$rs_u_file</span>){
            <span>return</span><span>false</span>;
        }
        <span>return</span><span>$file_id</span>;
    }</code>
Copy after login

Configuration file:

<code><span>'FILE_UPLOAD_CONFIG'</span>=><span>array</span>(
        <span>'mimes'</span> => <span>''</span>, <span>//允许上传的文件MiMe类型</span><span>'maxSize'</span> => <span>6</span> * <span>1024</span> * <span>1024</span>, <span>//上传的文件大小限制 (0-不做限制)</span><span>'exts'</span> => <span>array</span>(<span>'jpg'</span>, <span>'gif'</span>, <span>'png'</span>, <span>'jpeg'</span>),<span>// 设置附件上传类型</span><span>'autoSub'</span> => <span>true</span>, <span>//自动子目录保存文件</span><span>'subName'</span> => <span>array</span>(<span>'date'</span>, <span>'Y-m-d'</span>), <span>//子目录创建方式,[0]-函数名,[1]-参数,多个参数使用数组</span><span>'rootPath'</span> => <span>'./Uploads/'</span>, <span>//保存根路径</span><span>'savePath'</span> => <span>''</span>, <span>//保存路径</span><span>'saveName'</span>   =>    <span>array</span>(<span>'uniqid'</span>,<span>''</span>),
    ),</code>
Copy after login

function.php File

<code><span>/**
 * 返回json格式的数据到客户端
 *<span> @access</span> protected
 *<span> @param</span> mixed $data 要返回的数据
 *<span> @return</span> void
 */</span><span><span>function</span><span>jsonReturn</span><span>(<span>$data</span>)</span>{</span><span>$json_str</span> = json_encode(<span>$data</span>);
    <span>// 返回JSON数据格式到客户端 包含状态信息</span>
    header(<span>'Content-Type:application/json; charset=utf-8'</span>);
    <span>//处理json中包含的‘null’,将其替换成空字符串</span><span>$search</span> = <span>'null'</span>;
    <span>$replace</span> = <span>'""'</span>;
    <span>$returndata</span> = str_replace(<span>$search</span>, <span>$replace</span>, <span>$json_str</span>);
<span>//  testAddDataIntoTestTable(null,$returndata);</span><span>exit</span>(<span>$returndata</span>);
}</code>
Copy after login

The above introduces thinkphp (php) + Ajax to upload images, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template