thinkphp (php) + Ajax upload pictures
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>
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>
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>
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>
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>
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To learn more about open source, please visit: 51CTO Hongmeng Developer Community https://ost.51cto.com Running environment DAYU200:4.0.10.16SDK: 4.0.10.15IDE: 4.0.600 1. To create an application, click File- >newFile->CreateProgect. Select template: [OpenHarmony] EmptyAbility: Fill in the project name, shici, application package name com.nut.shici, and application storage location XXX (no Chinese, special characters, or spaces). CompileSDK10, Model: Stage. Device

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string. When writing programs in Golang, we often need to convert the structure into a JSON string. In this process, the json.MarshalIndent function can help us. Implement formatted output. Below we will explain in detail how to use this function and provide specific code examples. First, let's create a structure containing some data. The following is an indication

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach
