preface

When we use Typora for creation, the pictures in the article can be saved locally or uploaded to the map bed of the third-party service party.

If the images are saved locally, they won’t be displayed when we need to share our content with others on the Internet, and third-party image beds generally charge for them.

This article will share with you how to build a map bed of their own, welcome you interested developers to read this article.

Environment set up

In the preference configuration of Typora, we switch to the image column, as shown below:

  • At the position number 1 in the picture, you can select the behavior when the picture is inserted. After clicking on it, we can select the option of uploading the picture
  • In the no. 2 position in the picture, you can choose which graph bed client to use when uploading pictures. After clicking on it, we select uPic option

Install the diagram bed client

Go to the uPic project GitHub home page and download the installation package from the Releases page.

When the download is complete, unzip it and drag it to the application folder.

Configuring the Client

After opening the application, an icon will appear in the menu bar. After clicking, click “Preferences” in the options that appear, as shown below:

In the open interface, click the plus sign in the lower left corner, and click “Customize” in the popup options, as shown in the picture below:

After selecting custom, the following interface will appear:

Configuration required for uploading resources

Let’s take a look at the effects of the first four tags:

  • Number 1 is the address of the interface for uploading the service
  • Number 2 indicates the request mode of the interface
  • 3 indicates the field name when the interface parses the file stream
  • No. 4 is marked with other fields required when invoking the upload interface. The interface is as follows:

Note: We need to add a Header field with the key name: content-type and the value: multipart/form-data; charset=utf-8; .

If not, your interface will report an error.

The body field is the extra parameter you need to call the upload interface.

Obtain the configuration required for the resource

Next, let’s take a look at the other annotations:

  • The value 5 indicates the file path returned by the interface after the file is successfully uploaded. For example, if path is returned to {path:”/uploads/20199afrj.png”}, we need to fetch the value of [“path”]. If path is returned to {path:”/uploads/20199afrj.png”}, we need to fetch the value of [“path”]

  • Note 6 indicates the prefix of the domain name to be added after the uploaded file is obtained

  • After the configuration is complete, we can click verify to check whether the service is normal. If it is normal, you will see the following prompt:

Finally, click save in tag 7 and our configuration is complete.

Upload service

The upload service can be written in any backend language, as long as it follows the file upload specification. Since I only know Java as the backend language, this article uses the Java+SpringBoot framework as an example to write some sample code.

Control layer

Let’s take a look at the controller layer code, which looks like this:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.lk.service.FileUploadService;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
// Allow cross-domain access
@CrossOrigin()
@RequestMapping("/uploads")
public class FileUploadController {
    // Inject the file upload service
    @Resource(name = "FileUploadServiceImpl")
    private FileUploadService fileUploadService;
  
    @PostMapping("/singleFileUploadToPath")
    @ResponseBody
    public Map<String, Object> singleFileUploadToPath(@RequestParam("file") MultipartFile file, @RequestParam("path") String path) throws IOException {
        Map<String, Object> result = new HashMap<>(16);
        // Call the single file upload interface
        returnfileUploadService.singleFileUpload(file, path); }}Copy the code

In the above code, we accept two parameters:

  • File: indicates the uploaded file stream
  • Path: indicates the upload path

The interface layer

Next, let’s look at the code for the Service layer, as follows:

import org.springframework.web.multipart.MultipartFile;

// File upload interface
public interface FileUploadService {
      Map<String, Object> singleFileUpload(MultipartFile file, String path) throws IOException;
}
Copy the code

Implementation layer

Finally, let’s look at the code for the ServiceImpl layer, which looks like this:

import java.util.Map;
import com.lk.service.FileUploadService;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.HashMap;
import java.io.File;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.lk.utils.UUIDUtil;
import com.lk.utils.DateUtil;
import com.lk.utils.FileUtil;

@Slf4j
@Service("FileUploadServiceImpl")
public class FileUploadServiceImpl implements FileUploadService {
    // Read the file path from the configuration file
    @Value("${uploadFilePath}")
    private String fileBaseUrl;
    @Override
    public Map<String, Object> singleFileUpload(MultipartFile file, String path) throws IOException {
        return this.writeFile(file, path);
    }
  
    private Map<String, Object> writeFile(MultipartFile file, String path) throws IOException {
        String fileType = file.getContentType();
        long fileSize = file.getSize();
        log.info("[file type] - [{}]", fileType);
        log.info("[file name] - [{}]", file.getOriginalFilename());
        log.info("[file size] - [{}]", fileSize);
        / / file name
        String fileName = file.getOriginalFilename();
        assertfileName ! =null;
        // Generate the file name
        String finalFileName = UUIDUtil.getUUID()+fileName.substring(fileName.lastIndexOf("."));
        // Push file information to the client
        Map<String, Object> result = new HashMap<>(16);
        if(path.length() ! =0) {
            String dayTime = DateUtil.getTimeForDay();
            String writePath = fileBaseUrl + path + "/" + dayTime + "/";
            // If the path does not exist, create the path
            Boolean touchResult  = FileUtil.touchFolder(writePath);
            if(! touchResult) { result.put("code", -2);
                result.put("msg"."Server error: path creation failed");
                log.error("Failed to create upload path" + writePath);
                return result;
            }
            // Write to the specified path
            file.transferTo(new File(writePath + finalFileName));
            result.put("path", dayTime + "/" + finalFileName);
        } else {
            // Write the file to the default path
            file.transferTo(new File(fileBaseUrl + finalFileName));
        }
        result.put("code".0);
        result.put("data"."Upload successful");
        result.put("contentType", file.getContentType());
        result.put("fileName", finalFileName);
        result.put("fileSize", file.getSize() + "");
        returnresult; }}Copy the code

Figure bed client request header configuration

The upload service listed in the above code needs to transmit the path field in addition to the file field, so the configuration of the graph bed client is as follows:

Implementation effect

Finally, let’s take a look at what the configuration looks like:

Write in the last

At this point, the article is shared.

I’m an amazing programmer, a front-end developer.

If you are interested in me, please go to my personal website to learn more.

  • Feel free to correct any mistakes in the comments section, and if this post helped you, feel free to like and follow 😊
  • This article was originally published in Nuggets and cannot be reproduced without permission at 💌