编程知识 cdmana.com

Use spring boot + Vue + antd + US3 to build your own map bed in 10 minutes

Python The actual combat community

Java The actual combat community

Long press to identify the QR code below , Add as needed

Scan code, pay attention to add customer service

Into the Python community ▲

Scan code, pay attention to add customer service

Into the Java community

Author's notes

Source code maker notes (ID:majiangbiji)

There are already some good picture beds on the Internet , such as

  1. SM.MS https://sm.ms/

  2. Figure shell https://imgkr.com

  3. Passing by the drawing bed https://imgchr.com/

Then why do we have to build our own picture bed ? One of the reasons is that Manon always likes to toss , Second, it is more secure to have its own map bed data storage . Then we'll start . Here's the demo address , You can see the effect of the completion of the construction first .

https://xiaotuwo.github.io
Click the button to upload the picture , When you're done, you can copy links and download

Prepare the front-end environment

  1. install nodejs
    Go by yourself nodejs Download from the official website , We mainly use npm Tools .

  2. Install Taobao image , If it's at home , Downloading images is slow , So use the domestic image   .

sudo npm install -g cnpm --registry=https://registry.npm.taobao.org
  1. install vue-cli Tools
    Because we use the front end vue, So you need to install vue-cli

cnpm install -g @vue/cli
  1. Create project

vue create xiaotuwo
  1. add to antd rely on

cnpm install ant-design-vue --save
  1. start-up

cd xiaotuwo  
npm run serve  
  1. visit , Be able to access HelloWorld The page shows that our environment has been successfully prepared .

http://localhost:8080

Write front end code

By now, our basic environment has been built , Now start to write the front-end code . We are based on sm.ms Build as a prototype . As shown in the figure below, we only edit his head , Upload part and tail

The shape of the finished product is as follows , hold sm.ms The interactive design of dragging and uploading pictures has been changed to clicking and uploading pictures , But if you want to achieve drag and drop is also very simple , Here is antd The style of , Just change the label .
https://www.antdv.com/components/upload-cn/

The head and tail code is very simple , We'll just talk about uploading part of the code . Set up well vue The framework will go to the one provided above later antd I found it in the website of upload Control , Click directly to copy your favorite code style , Paste the content/index.vue Just inside , And then modify a-upload Of action For their own server address can , Local testing is http://localhost:8887/api/images/upload, There are also supporting server code below .

vue The grammar is not specific , It's about a place , handlePreview Method, I added a logic to copy the link , You can easily click on the preview to copy the image link , This is convenient to put the URL into other places to use .

his.$message.success(' Copy image link succeeded ');
document.addEventListener("copy"function copyCall(e{
  e.preventDefault()
  e.clipboardData.setData("text/html", file.preview)
  e.clipboardData.setData("text/plain", file.preview)
  document.removeEventListener("copy", copyCall)
})

Here, the basic front-end construction is completed , You can check the source code directly
https://github.com/xiaotuwo/xiaotuwo-client

Server side environment preparation

This article uses US3 Set up the map bed , at present US3 Yes 20G Free storage and Every month 20G Free traffic , It's enough for self use and starting .

Copy the link below to the browser to view US3 Official website , First entry requires registration
https://urlify.cn/YNNBNn
After registration , Go to the console to create US3 Space

Enter the space and fill in the storage name , Private space and open space are OK , I created xiaotuwo.cn-bj.ufileos.com Keep it in reserve .

stay US3 Console create token , It's mainly used to upload , Delete images using

Choose the space you just created , Set the age limit and click OK , Remember to check the token permission

Click Finish to get the public key and private key , Copy standby

Write server code

The server code is mainly divided into three parts
1、 To receive a request Controller
2、 Upload pictures to US3 The logic of
3、 Back to content processing


1、 To write Controller
Use MultipartHttpServletRequest Received from the front end file file , call uCloudProvider Upload .

@PostMapping({"/api/files/upload"})
    @ResponseBody
    public FileDTO upload(HttpServletRequest request) {
        FileDTO resultFileDTO = new FileDTO();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        long start = System.currentTimeMillis();
        try {
            if (file == null) {
                resultFileDTO.setStatus("error");
            }
            FileDTO fileDTO = uCloudProvider.uploadWithExpired(file.getInputStream(), file.getContentType(), Objects.requireNonNull(file.getOriginalFilename()));
            log.info("UPLOAD_FILE_EXPIRED|ip:{}|referer:{}|url:{}|cost:{}", getIpAddress(request), request.getHeader("referer"), fileDTO.getUrl(), System.currentTimeMillis() - start);
            executorService.submit(new UCloudScanner(fileDTO, uCloudProvider, executorService, 1));
            resultFileDTO.setName(fileDTO.getName());
            resultFileDTO.setUrl(fileDTO.getUrl());
            resultFileDTO.setThumbUrl(fileDTO.getUrl());
            resultFileDTO.setStatus("done");
        } catch (Exception e) {
            log.error("UPLOAD_FILE_ERROR", e);
            resultFileDTO.setStatus("error");
        }
        return resultFileDTO;
    }

2、 Upload pictures to US3 The logic of
Upload US3 Mainly some configuration files , I use it directly Maven Of Filter Handle , Configuration file in pom.xml Inside , Write... At compile time application.properties

<id>dev</id>
<properties>
    <server.port>8887</server.port>
    <ucloud.ufile.public-key> Your public key </ucloud.ufile.public-key>
    <ucloud.ufile.private-key> Your private key </ucloud.ufile.private-key>
    <ucloud.ufile.upload-domain-private> Yours bucket name .cn-bj.ufileos.com</ucloud.ufile.upload-domain-private>
    <ucloud.ufile.download-domain-private> Yours bucket name .cn-bj.ufileos.com</ucloud.ufile.download-domain-private>
    <ucloud.uaicensor.publicKey> Jianhuang public key </ucloud.uaicensor.publicKey>
    <ucloud.uaicensor.privateKey> Jianhuang private key </ucloud.uaicensor.privateKey>
    <ucloud.uaicensor.resourceId> Chi Huang ID</ucloud.uaicensor.resourceId>
    <ucloud.uaicensor.url>http://api.uai.ucloud.cn/v1/image/scan</ucloud.uaicensor.url>
</properties>
<activation>
    <activeByDefault>true</activeByDefault>
</activation>

We will find that in the configuration file, in addition to the file configuration, there is also a set of yellow identification configuration , Yes, this is not the point of this article , But the map bed must have the ability to learn from the Yellow River , Specific implementation can refer to the article To climb up in anger Hub Resources provide a platform to learn from the Yellow River
Specifically US3 The logic code is also very simple , The main logic is to upload , Use the private key and timestamp to generate links , Show .

public FileDTO upload(InputStream fileStream, String mimeType, String fileName) {
        String generatedFileName;
        String[] filePaths = fileName.split("\\.");
        if (filePaths.length > 1) {
            generatedFileName = UUID.randomUUID().toString() + "." + filePaths[filePaths.length - 1];
        } else {
            throw new ErrorCodeException(ErrorCode.FILE_UPLOAD_FAIL);
        }
        long start = System.currentTimeMillis();
        try {
            log.debug("UCloudProvider start upload file, filename : {}, time : {}", fileName, new Date());
            ObjectAuthorization objectAuthorization = new UfileObjectLocalAuthorization(publicKey, privateKey);
            ObjectConfig config = new ObjectConfig(uploadDomainPrivate);
            PutObjectResultBean response = UfileClient.object(objectAuthorization, config)
                    .putObject(fileStream, mimeType)
                    .nameAs(generatedFileName)
                    .toBucket(bucketNamePrivate)
                    .setOnProgressListener((bytesWritten, contentLength) -> {
                    })
                    .execute();
            log.debug("UCloudProvider end upload file, filename : {}, time : {}, cost : {}", fileName, new Date(), System.currentTimeMillis() - start);
            if (response != null && response.getRetCode() == 0) {
                long start2 = System.currentTimeMillis();
                log.debug("UCloudProvider start get url, filename : {}, time : {}", fileName, new Date());

                String url = UfileClient.object(objectAuthorization, new ObjectConfig(downloadDomainPrivate))
                        .getDownloadUrlFromPrivateBucket(generatedFileName, bucketNamePrivate, 24 * 60 * 60)
                        .createUrl();

                log.debug("UCloudProvider end get url, filename : {}, time : {}, cost : {}", fileName, new Date(), System.currentTimeMillis() - start2);

                FileDTO fileDTO = new FileDTO();
                fileDTO.setUrl(url.replace("http""https"));
                fileDTO.setName(generatedFileName);
                return fileDTO;
            } else {
                log.debug("UCloudProvider end upload file, filename : {}, time : {}, cost : {}", fileName, new Date(), System.currentTimeMillis() - start);
                log.error("upload error,{}", response);
                throw new ErrorCodeException(ErrorCode.FILE_UPLOAD_FAIL);
            }
        } catch (UfileClientException | UfileServerException e) {
            log.debug("UCloudProvider end upload file, filename : {}, time : {}, cost : {}", fileName, new Date(), System.currentTimeMillis() - start);
            log.error("upload error,{}", fileName, e);
            throw new ErrorCodeException(ErrorCode.FILE_UPLOAD_FAIL);
        }
    }

3、 Back to content processing , Here, too, we need to pay attention to , In order to cooperate antd Of upoad Control , our dto as follows

@Data
public class FileDTO {
    private String name;
    private String status;
    private String url;
    private String thumbUrl;
}

Server side source code access
https://github.com/xiaotuwo/xiaotuwo-server

It's all over here , Have you learned ? If there are any questions , You can go to US3 My own official forum  
https://uclub.ucloud.cn/invite/93

 Programmer column   Scan code and pay attention to customer service   Press and hold to recognize the QR code below to enter the group 

Recent highlights are recommended :  

  Another programmer , Caught !( Real events )

  What kind of experience is it for a programmer to have a cute girlfriend ?

 “12306” How awesome is the architecture of ?

 csv A simple solution to the problem of file reading and writing garbled code


Here's a look Good articles to share with more people ↓↓

版权声明
本文为[osc_ bskubcvl]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225130401782H.html

Scroll to Top