Laravel + Layer implements Image Upload (finishing ),

Source: Internet
Author: User

Laravel + Layer implements Image Upload (finishing ),

♩Background

Yesterday at your ownLaravel5.5In the Framework project, you want to integrateLayerHoweverajax(POST)Always show when submitting a request500Error

 ♪Analysis

Region Problem

 

Finally, extract the core code and place it inLarvelRun outside the framework and find that the code is correct, becauseLaravelThe framework is too exposed and ignored.CSRFLimits

Solution

A hidden input box is usually stored when a form is submitted.

<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">

Or add a line of code to the form to be submitted:

<form method="POST" action="/profile"> {{ csrf_field() }} ...</form>

HoweverajaxWe recommend that you use the following method when submitting

1. Add hidden domains to the page

<input type="hidden" name="_token" class="tag_token" value="<?php echo csrf_token(); ?>">

②. Before ajax requests, obtaincsrf_token()Value

var tag_token = $(".tag_token").val();

③ In an ajax request, the value is transmitted as part of the data, for example:

data:{'_token':tag_token}

♫Steps

 Sources source file directory

Prepare the Supervisor

Introduce css and js files of layui to the page

<script type="text/javascript" src="layui/layui.js"></script><script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><link rel="stylesheet" type="text/css" href="layui/css/layui.css" rel="external nofollow" />

Note: The source code package of the layui framework downloaded by myself islayui-v2.2.45

Core code:

<Div class = "layui-form-item"> <div class = "layui-upload"> <button type = "button" name = "img_upload" class = "layui-btn btn_upload_img "> <I class =" layui-icon "> </I> upload an image </button>  <p id = "demoText"> </p> </div>

Js Code:

<Script type = "text/javascript"> layui. use ('upload', function () {var upload = layui. upload; var tag_token = $ (". tag_token "). val (); // normal Image upload var uploadInst = upload. render ({elem :'. btn_upload_img ', type: 'images', exts: 'jpg | png | gif' // you can specify some suffixes to demonstrate frontend verification and backend verification. //, auto: false // select whether to upload the image directly. //, accept: 'images' // specifies the file type to be uploaded. url: 'upload. php ', data: {' _ token': tag_token}, before: function (obj) {// preread local file example. ie8 obj is not supported. preview (function (index, file, result) {$ ('. img-upload-view '). attr ('src', result); // image Link (base64)}) ;}, done: function (res) {// if the upload fails if (res. status = 1) {return layer. msg ('uploaded successfully');} else {// layer uploaded successfully. msg (res. message) ;}}, error: function () {// demonstrate the failure status and implement retransmission return layer. msg ('upload failed, upload again ') ;}}) ;}); </script>

Worker backend Processing

Because the default frontend Layer isPOSTRequest, then the backgrounduplaod.phpThe core code is as follows:

If ($ _ POST) {// Image Upload operations $ file_name = $ _ FILES ['file'] ['name']; // $ file_type = $ _ FILES ["file"] ["type"]; $ file_tmp = $ _ FILES ["file"] ["tmp_name"]; $ file_error = $ _ FILES ["file"] ["error"]; $ file_size = $ _ FILES ["file"] ["size"]; if ($ file_error> 0) {// error $ message = $ file_error;} elseif ($ file_size> 1048576) {// The file is too large. $ message = "the uploaded file cannot exceed 1 MB";} else {$ date = date ('ymmd'); $ file_name_arr = explode ('. ', $ File_name); $ new_file_name = date ('ymdhis '). '. '. $ file_name_arr [1]; $ path = "upload /". $ date. "/"; $ file_path = $ path. $ new_file_name; if (file_exists ($ file_path) {$ message = "this file already exists";} else {// TODO to check whether the current directory exists, create a new one if it does not exist! If (! Is_dir ($ path) {mkdir ($ path, 0777);} $ upload_result = move_uploaded_file ($ file_tmp, $ file_path ); // This function only supports files uploaded through http post if ($ upload_result) {$ status = 1; $ message = $ file_path;} else {$ message = "File Upload Failed, please try again later ";}}} else {$ message =" parameter error ";} return showMsg ($ status, $ message );

Note ]:Use the downloaded source code file to replace the core code.

Supplement Public FunctionsshowMsg():

function showMsg($status,$message = '',$data = array()){ $result = array( 'status' => $status, 'message' =>$message, 'data' =>$data ); exit(json_encode($result));}

Effect of Compaction

♬Supplement

The Code provided by considerations, which can be usedPHPNative Development or other popular frameworks, as long as the background can receive$_FILESData is easy. I just got stuck.LaravelFrameworkCSRFAuthentication takes a lot of time, so:

<! -- If the Laravel framework is used, open the following sentence! --> <! -- <Input type = "hidden" name = "_ token" class = "tag_token" value = "<? Php/* echo csrf_token (); */?> "> -->

The image upload function of backend code is a native program and can be optimized by itself. We recommend that you use the integration method recommended by popular frameworks. Bytesmove_uploaded_file()Supplement

Note the following for the above Code:move_uploaded_file()Use of methods

If the directory uploaded by the image does not exist, an error may be reported. Therefore, you must determine the current situation. If the directory does not exist, create a new directory.

// TODO checks whether the current directory exists. If not, create a new directory! If (! Is_dir ($ path) {mkdir ($ path, 0777 );}

As a popular framework developed by PHP, the processing in ⒊ Laravel must integrate the file upload function and upload files. For more information, see the learning document. Take my own processing as an example:

(1). the file will be stored"storage"Directory, and further access to this directory also needs to add soft links, it feels a bit of trouble, so I specify the disk"public"Directory.

(2) refer to my previous article-Implementation of the Laravel file upload function to open the configuration file.config/filesystems.phpTo add a url to the disk configuration array.

'upload' => [  'driver' => 'local',  'root' => public_path('upload/image/'.date('Ymd')), ],

(3) the corresponding background core processing code is:

Public function img_file (Request $ request) {$ status = 0; $ data = []; if ($ request-> method () = 'post ') {$ date = date ('ymmd'); $ path = $ request-> file ('file')-> store ('', 'upload '); if ($ path) {$ fileUrl = '/upload/image /'. $ date. '/'. $ path; $ status = 1; $ data ['url'] = $ fileUrl; $ message = 'upload succeeded ';} else {$ message = "Upload Failed ";}} else {$ message = "parameter error";} return showMsg ($ status, $ message, $ data );}

In this way, the Directory of the uploaded image is:public/upload/image/{$date}/

☺Source code download

Download source code

Summary

The above section describes how to use Laravel + Layer to upload images (finishing). I hope it will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.