We use SpringBoot to achieve file upload, the SpringBoot environment in this article and SpringBoot+MyBatis+ general Mapper environment is basically the same, we will not repeat the wheel, but directly start this function.

Rely on

We’ve already introduced Web development-related dependencies in SpringBoot+MyBatis+ Universal Mapper, so we don’t need to introduce them here.

configuration

We need to configure SpringMVC’s file upload functionality with properties like MaxFileSize and so on. UploadConfig: JavaConfig configuration class UploadConfig: JavaConfig

@Configuration
public class UploadConfig {

    @Bean
    public MultipartConfigElement multipartConfigElement(a) {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // Single data size
        factory.setMaxFileSize("10240KB");
        /// Total uploaded data size
        factory.setMaxRequestSize("102400KB");
        returnfactory.createMultipartConfig(); }}Copy the code

We then customize some configurations in the application.yml file:

file:
  upload:
    path: G:\temp\images\   # File upload target path
    allowTypes:             Type of file upload allowed
      - image/jpeg
      - image/png
      - image/bmp
Copy the code

Read the configuration into a Java file using ConfigurationProperties:

@Data
@Component
@ConfigurationProperties(prefix = "file.upload")
public class UploadProperties {
    private String path;
    private List<String> allowTypes;
}
Copy the code

code

Before writing the file upload code, we also need to do some preparatory work, such as preparing some tool classes, which can facilitate us to achieve the file upload function.

Write utility classes

  • Unique ID generator, can generate a unique ID.
public class IDUtils {

    /** * unique ID generator, can generate a unique ID *@return* /
    public static String generateUniqueId(a) {
        returnUUID.randomUUID().toString()+System.currentTimeMillis(); }}Copy the code
  • File name replacement tool, used to replace file names, avoid file name duplication caused by the same name will be overwritten.
public class UploadUtils {

    /** * File name replacement tool to replace file names with random names *@param oldName
     * @return* /
    public static String generateFileName(String oldName){
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        returnIDUtils.generateUniqueId()+suffix; }}Copy the code

Write the Web tier

@RestController
@RequestMapping("upload")
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @PostMapping("image")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
        returnResponseEntity.ok(uploadService.uploadImage(file)); }}Copy the code

Write the Service layer

  • The Service interface layer
public interface UploadService {

    /** * upload image *@param file
     * @return* /
    String uploadImage(MultipartFile file) throws Exception;
}
Copy the code
  • The Service layer
 @Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private UploadProperties uploadProperties;

    @Override
    public String uploadImage(MultipartFile file) throws IOException {
        if(! uploadProperties.getAllowTypes().contains(file.getContentType())){throw new IOException("Incorrect file upload type!");
        }
        String fileName = UploadUtils.generateFileName(file.getOriginalFilename());
        file.transferTo(new File(uploadProperties.getPath()+fileName));
        returnfileName; }}Copy the code

test

Since we didn’t write an HTML file either, we used Postman directly to test it.

Step 1: We use a POST request with a path of /upload/image.

Note that we need to set the content in the request header to empty.

Step 2: We carry the file in the request body.

Step 3: Make a request.