This is the 31st day of my participation in the August Text Challenge.More challenges in August

A file upload server solution

1.1 Disadvantages of uploading files directly to the server

1. If the file is uploaded through our server, it will occupy the bandwidth of the server. 2. If the file is uploaded to the server, it will occupy the space of our server’s hard disk.

1.2 Solutions

We can use third-party storage, such as the object storage of Ali Cloudoss. Let third-party storage host our files. First go to Ali Cloud to open the object storageOSS. The object storage device is enabledOSSManagement Console:


Once inside, we go to buy resource packs:


1.3 the Bucket concept

We’ll look at this after we buy itBucketThe concept, you can just put itossA remote computer, where we store our files, andBucketIt is equivalent to computer disk partition. You can divide the documents into different disks. So let’s create one for our projectBucketLibrary: Note that this area is best chosen in the area where your server is located, to reduce some costs. Some functions of the test project are not open, the project really online is best to open.


To create theBucketAfter that, we’ll go straight to its usage documentation, We certainly don’t use it on our endsdkBecause this way of words have disadvantages, since we useOSSStorage is not through the server, reduce service bandwidth, and storage space pressure, and use thissdkAgain, the client sends the request to the server, and then the server takes the file and requests it to be saved toOSSStore. This method still consumes the server’s bandwidth and storage space. There’s no point. We recommend going straight to best practice examples to do this:

bywebThe end uploads data directly to oursOSSIn the cloud storage system, the bandwidth and storage space of the server are reduced.


1.4 Client Demo

Download the browser client code:Let’s go straight to the download example:


Open it in an editorupload.jsAs you can seeaccessidandaccesskeyDirect exposure to the browser is very dangerous.Regardless of its security, let’s use this example to demonstrate running, and then server side signature optimization: click on personal information to findaccesskey: accesskeyIs very high, so it is recommended to create a subuseraccesskey, so that even if it is a sub-user of the leak, we can also take sub-usersaccesskeyDelete to be safe: The user remembers the information after it is created because it is only displayed once. After creating a user, grant permissions to the user:


thenupload.jsIn theaccessidandaccesskeyReplace it with the one you just createdaccessidandaccesskey.hostTo choose usBucketThe domain name:


Then, inBucketModify permission Settings to set cross-domain issues: Modify thedemoExpiration time in:


1.5 Test Effect

2. Use back-end signature (best practice)

We use the third party directlyPackagistGo and find out aboutlaravelRelated:Run the setup command:composer require "iidestiny/laravel-filesystem-oss";


Add driver to filesystems.php config file:

'oss'= > ['driver'= >'oss'.'root'= >' '.// Set the upload root prefix
            'access_key' => env('OSS_ACCESS_KEY'),
            'secret_key' => env('OSS_SECRET_KEY'),
            'endpoint'   => env('OSS_ENDPOINT'), // Use SSL. For example: https://oss-cn-beijing.aliyuncs.com
            'bucket'     => env('OSS_BUCKET'),
            'isCName'    => env('OSS_IS_CNAME'.false), // If isCname is false, the OSS domain name should be set to the endpoint, for example: 'oss-cn-beijing.aliyuncs.com', otherwise it is a customized domain name, and CNAME or CDN please go to ali OSS background to configure and bind bucket
            // If there are more buckets to switch, add all buckets, not buckets
            'buckets'= > ['test'= > ['access_key' => env('OSS_ACCESS_KEY'),
                    'secret_key' => env('OSS_SECRET_KEY'),
                    'bucket'     => env('OSS_TEST_BUCKET'),
                    'endpoint'   => env('OSS_TEST_ENDPOINT'),
                    'isCName'    => env('OSS_TEST_IS_CNAME'.false)],/ /...]],Copy the code


Then, in.envAdd:

OSS_ENDPOINTIs the domain name of the region node:


Then the token is generated. Define a route in auth.php to authenticate user auth.php:

  // Ali cloud OSS token
  $api->get('oss/token', [OssController::class, 'token']);
Copy the code


To create a controller, run:php artisan make:controller Auth/OssController :OssController.phpWrites:


      

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class OssController extends BaseController
{
    /** * Generate oss upload token */
    public function token()
    {
        $disk = Storage::disk('oss');

        /** * 1. Prefixes like 'images/' * 2. Callback server URL * 3. 4. The validity period of the current direct transmission configuration link */
        $config = $disk->signatureConfig($prefix = '/'.$callBackUrl = ' '.$customData= [].$expire = 30);
        $configArr = json_decode($config.true);
        return $this->response->array($configArr); }}Copy the code

Testing:


Pass these fetched configurations in the front end:


Image configuration complete domain name: in.envaddossDomain prefix:config/filesystems.phpAdd:


In the commodityGoodTransformer.phpAdd:


Helpers.php: helpers.php: helpers.php: helpers.php: helpers.php: helpers.php: helpers.php: helpers.php: helpers.php: helpers.php

    /** * Clear all class caches */ 
    if(! function_exists('oss_url')) {
        function oss_url ($key) {
            return config('filesystems.disks.oss.bucket_url').$key; }}Copy the code

Then changeGoodTransformer.php:Effect:This is what happens to images everywhere else. Ex. :Effect:useossAs a best practice, in the case of the image name, the front end provides the image name, and then the field returns the concatenated field to be displayed.

If you find this article helpful on your way to learning PHP, please follow me to like and comment on it. Thank you, your blog is definitely another support for me to write.