In recent projects, files need to be uploaded and downloaded through OSS, which is hereby recorded for future reference.

First, you need to open the OSS service of Ali Cloud and register the relevant configuration information: endPoint, accessKeyId, accessKeySecret, bucketName.

1. Introduce dependencies

<! --aliyunOSS--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.11. 0</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.31.</version>
</dependency>
Copy the code

2. Properties configuration

# oss file.client.type=oss # oss file.oss.//oss-cn-hangzhou.aliyuncs.comAccessKeyId = Go to the OSS console to obtain file. Oss. accessKeySecret= Go to the OSS console to obtain file file.oss.rootDir=dataCopy the code

3. Boot class configuration

/** * boot class **@author zhangzhixiang
 * @date2018/09/18 14:51:39 * /
@Configuration
public class BootstrapConsts {
    
    @Value("${file.client.type}")
    private String fileClientType;
       
    @Value("${file.oss.endPoint}")
    private String endPoint;

    @Value("${file.oss.accessKeyId}")
    private String accessKeyId;
    
    @Value("${file.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${file.oss.bucketName}")
    private String bucketName;

    @Value("${file.oss.rootDir}")
    private String rootDir;
    
    /** * File client type */
    public static String file_client_type;
    /** * OSS address (different server, different address) */
    public static String end_point;
    /** * OSS key id (go to the OSS console) */
    public static String access_key_id;
    /** * OSS key (go to the OSS console) */
    public static String access_key_secret;
    /** * OSS bucket name */
    public static String bucket_name;
    /** * OSS root directory */
    public static String root_dir;
    
    @PostConstruct
    private void initial(a) { file_client_type = fileClientType; end_point = endPoint; access_key_id = accessKeyId; access_key_secret = accessKeySecret; bucket_name = bucketName; root_dir = rootDir; }}Copy the code

4, file factory class

/** * File operation client generate class **@author zhangzhixiang
 * @data2018/09/14 11:56:43 * /
public class ClientFactory {

    private static final Logger logger = LoggerFactory.getLogger(ClientFactory.class);

    /** * Get file by type operation client **@param type
     * @return* /
    public static FileClient createClientByType(String type) {
        FileClient client = null;
        switch (type) {
            case "local":
                client = LocalClient.create();
                break;
            case "oss":
                client = OssClient.create();
                break;
            default:
                client = null;
                logger.info("the type of fileClient does not exist.please check the type.type={}", type);
                break;
        }
        returnclient; }}Copy the code

5. File interface

/** * Local file manipulation class **@author zhangzhixiang
 * @data2018/09/14 11:56:43 * /
public interface FileClient {
    
    /** * get file stream **@author zhangzhixiang
     * @date 2018/10/17 10:59:43
     * @param code
     * @return java.io.InputStream
     */
     InputStream getFileStream(String code);

    /** * Upload file **@param inputStream
     * @param filePath
     * @param ext
     * @author zhangzhixiang
     * @date 2018/10/17 10:59:43
     * @return boolean
     */
     String upload(InputStream inputStream, String filePath, String ext) throws Exception;

    /** * Download file **@param response
     * @param filePath
     * @param name
     * @author zhangzhixiang
     * @date 2018/10/17 10:59:43
     * @return void
     */
     void download(HttpServletResponse response, String filePath, String name) throws Exception;

    /** * delete file **@param dirPath
     * @author zhangzhixiang
     * @date 2018/10/17 10:59:43
     * @return void
     */
     void delete(String dirPath);

    /** * get the url **@param key
     * @author zhangzhixiang
     * @date 2018/10/17 10:59:43
     * @return java.lang.String
     */
     String getUrl(String key);

}
Copy the code

Constant class definition

/ * * *@Description: Simple on definition *@Author: zhangzhixiang *@CreateDate: 2018/08/31 11:34:56 *@Version: 1.0 * /
public class SimpleConsts {
    
    public static final Integer INPUT_BUFFER_SIZE = 8192;

}
Copy the code

7. Configure the OSS client

/ * * *@Description: OSS client configuration *@Author: zhangzhixiang *@CreateDate: 2018/08/31 11:34:56 *@Version: 1.0 * /
public class OssClient implements FileClient {

    private static final Logger logger = LoggerFactory.getLogger(OssClient.class);

    private final char PATH_SEPARATOR = System.getProperty("file.separator").toCharArray()[0];

    private static OssClient ossClient;
    
    / * * *@Description: Gets the aliOSS object *@Author: zhangzhixiang * /
    private OSS getClient(a) {
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(BootstrapConsts.end_point, BootstrapConsts.access_key_id, BootstrapConsts.access_key_secret);
        } catch(Exception e){
            logger.error("**********************OSSClient bean create error.**********************",e);
            ossClient = null;
        }
        return ossClient;
    }

    / * * *@Description: Create OssClient *@Author: zhangzhixiang * /
    public static FileClient create(a) {
        if(null == ossClient) {
            synchronized (logger) {
                if(null == ossClient) {
                    ossClient = newOssClient(); }}}return ossClient;
    }

    / * * *@DescriptionGet the file stream according to code@Author: zhangzhixiang * /
    @Override
    public InputStream getFileStream(String code) {
        OSS aliOssClient = getClient();
        OSSObject ossObject = aliOssClient.getObject(BootstrapConsts.bucket_name, BootstrapConsts.root_dir + PATH_SEPARATOR + code);
        return ossObject.getObjectContent();
    }

    / * * *@Description: Upload files *@Author: zhangzhixiang * /
    @Override
    public String upload(InputStream inputStream, String code, String ext) {
        OSS aliOssClient = getClient();
        code = UUIDUtils.getUUID();
        PutObjectResult putResult = aliOssClient.putObject(BootstrapConsts.bucket_name, BootstrapConsts.root_dir + PATH_SEPARATOR + code + ext, inputStream);
        aliOssClient.shutdown();
        return StringUtils.isNotEmpty(putResult.getETag()) ? BootstrapConstss.root_dir + PATH_SEPARATOR + code + ext : null;
    }

    / * * *@Description: Download files *@Author: zhangzhixiang * /
    @Override
    public void download(HttpServletResponse response, String code, String name) {
        OSS aliOssClient = getClient();
        OSSObject ossObject = aliOssClient.getObject(BootstrapConsts.bucket_name, BootstrapConsts.root_dir + PATH_SEPARATOR + code);
        try (InputStream fis = ossObject.getObjectContent(); OutputStream fos = response.getOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(fos)) {
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.setHeader("Content-disposition"."attachment; filename=" + new String(name.getBytes("UTF-8"), "ISO-8859-1"));
            int bytesRead = 0;
            byte[] buffer = new byte[SimpleConsts.INPUT_BUFFER_SIZE];
            while((bytesRead = fis.read(buffer, 0, SimpleConsts.INPUT_BUFFER_SIZE)) ! = -1) {
                bos.write(buffer, 0, bytesRead);
            }
            bos.flush();
        } catch (Exception e){
            logger.error("**********************OssClient-->download throw Exception.name:{},code:{}**********************", name, code, e);
        }
        aliOssClient.shutdown();
    }

    / * * *@Description: Deletes files *@Author: zhangzhixiang * /
    @Override
    public void delete(String code) {
        OSS aliOssClient = getClient();
        boolean flag = aliOssClient.doesObjectExist(BootstrapConsts.bucket_name, code);
        if(false == flag) {
            logger.info("**********************The object represented by key:{} does not exist in bucket:{}.**********************", code, BootstrapConsts.bucket_name);
        }
        aliOssClient.deleteObject(BootstrapConsts.bucket_name, code);
    }

    / * * *@Description: Gets the file address *@Author: zhangzhixiang * /
    @Override
    public String getUrl(String code) {
        OSS aliOssClient = getClient();
        // Set the URL expiration time to 10 years
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        / / generated URL
        URL url = aliOssClient.generatePresignedUrl(BootstrapConsts.bucket_name, code, expiration);
        if(url ! =null) {
            return url.toString();
        }
        return null;
    }

    / * * *@Description: Generates the file name *@Author: zhangzhixiang * /
    private String createFileName(String ext) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return simpleDateFormat .format(new Date()) + (int)(Math.random() * 900 + 100) + ext;
    }
    
    / * * *@Description: Generates the unique identifier of OSS files *@Author: zhangzhixiang * /
    private String generateKey(String filename) {
        StringBuffer buffer = new StringBuffer();
        try {
            buffer.append(filename);
            buffer.append(Math.random());
            return EncodeUtil.encodeFromMD5ToBase64(buffer.toString());
        } catch(NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch(UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null; }}Copy the code

8, UUIDUtils class

/ * * *@author zxzhang on 2020/8/1
 */
public class UUIDUtils {

    /** * 32-bit default length of uUID **@param
     * @return java.lang.String
     * @author zxzhang
     * @date2020/8/1 * /
    public static String getUUID(a) {
        return UUID.randomUUID().toString().replace("-"."");
    }

    /** * get the specified length uuid **@param len
     * @return java.lang.String
     * @author zxzhang
     * @date2020/8/1 * /
    public static String getUUID(int len) {
        if (0 >= len) {
            return null;
        }

        String uuid = getUUID();
        System.out.println(uuid);
        StringBuffer str = new StringBuffer();

        for (int i = 0; i < len; i++) {
            str.append(uuid.charAt(i));
        }

        returnstr.toString(); }}Copy the code

9. Configure local clients

/ * * *@Description: Local client configuration *@Author: zhangzhixiang *@CreateDate: 2018/10/18 11:47:36 *@Version: 1.0 * /
public class LocalClient implements FileClient {

    private static final Logger logger = LoggerFactory.getLogger(LocalClient.class);

    private final char PATH_SEPARATOR = System.getProperty("file.separator").toCharArray()[0];

    private static LocalClient client;

    private LocalClient(a) {}

    / * * *@Description: Creates a client *@Author: zhangzhixiang * /
    public static FileClient create(a) {
        if(null == client) {
            synchronized (logger) {
                if(null == client) {
                    if(null == client) {
                        client = newLocalClient(); }}}}return client;
    }

    / * * *@Description: Get file stream *@Author: zhangzhixiang * /
    @Override
    public InputStream getFileStream(String code) {
        return null;
    }

    / * * *@Description: Upload files *@Author: zhangzhixiang * /
    @Override
    public String upload(InputStream inputStream, String filePath, String ext) throws Exception {
        File dir = new File(filePath);
        FileOutputStream out = null;
        try {
            if(! dir.exists()) { dir.mkdirs(); } filePath = filePath + PATH_SEPARATOR + createFileName(ext); File file =new File(filePath);
            out = new FileOutputStream(file);
            int b = 0;
            byte[] buffer = new byte[512];
            while((b = inputStream.read(buffer)) ! = -1) {
                out.write(buffer, 0, b);
            }
            out.flush();
            return filePath;
        } catch (IOException e) {
            logger.info("**************************LocalClient-->upload throw Exception.filePath:{}**************************", filePath);
            throw e;
        } finally {
            if(out ! =null) {
                out.close();
            }
            if(inputStream ! =null) { inputStream.close(); }}}/ * * *@Description: Download files *@Author: zhangzhixiang * /
    @Override
    public void download(HttpServletResponse response, String filePath, String name) throws Exception {
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.setHeader("Content-disposition"."attachment; filename=" + new String(name.getBytes("UTF-8"), "ISO-8859-1"));
        File file = new File(filePath + PATH_SEPARATOR + name);
        try (InputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); OutputStream fos = response.getOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(fos)) {
            int bytesRead = 0;
            byte[] buffer = new byte[SimpleConsts.INPUT_BUFFER_SIZE];
            while ((bytesRead = bis.read(buffer, 0, SimpleConsts.INPUT_BUFFER_SIZE)) ! = -1) {
                bos.write(buffer, 0, bytesRead);
            }
            bos.flush();
        } catch(Exception e) {
            logger.info("**************************LocalClient-->download throw Exception.filePath:{}**************************", filePath); }}/ * * *@Description: Deletes files *@Author: zhangzhixiang * /
    @Override
    public void delete(String dirPath) {
        File dir = new File(dirPath);
        if (dir.exists()) {
            if(dir.isFile()) {
                dir.delete();
            } else {
                File[] tmp = dir.listFiles();
                for(int i = 0; i < tmp.length; i++) {
                    if (tmp[i].isDirectory()) {
                        delete(dirPath + PATH_SEPARATOR + tmp[i].getName());
                    } else{ tmp[i].delete(); } } dir.delete(); }}}/ * * *@Description: Gets the file address *@Author: zhangzhixiang * /
    @Override
    public String getUrl(String key) {
        return null;
    }

    / * * *@Description: Generates the file name *@Author: zhangzhixiang * /
    private String createFileName(String ext) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return simpleDateFormat.format(new Date()) + (int) (Math.random() * 900 + 100) + ext; }}Copy the code

10, the controller layer

/ * * *@Description: File interface -controller *@Author: zhangzhixiang *@CreateDate: 2018/10/18 11:47:36 *@Version: 1.0 * /
@RestController
@RequestMapping("/api/ops/file")
public class FileController extends ExceptionHandlerAdvice {
    
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    / * * *@Description: File upload *@Author: zhangzhixiang * /
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseResult upload(@RequestParam("file") MultipartFile file) throws Exception {
        Map<String, String> map = new HashMap<>(64);
        FileClient fileClient = ClientFactory.createClientByType(BootstrapConsts.file_client_type);
        String ext = this.getExtName(file.getOriginalFilename());
        String code = fileClient.upload(file.getInputStream(), "/", ext);
        String url = fileClient.getUrl(code);
        map.put("code", code.substring(code.lastIndexOf("/") + 1).substring(code.lastIndexOf("\ \") + 1));
        map.put("url", url);
        return new ResponseResult().setSuccess(true).setData().setCode(ResultCode.SUCCESS.getCode());
    }

    / * * *@Description: File download *@Author: zhangzhixiang * /
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseResult download(@RequestParam("code") String code, @RequestParam("name") String name, HttpServletResponse response) throws Exception {
        FileClient fileClient = ClientFactory.createClientByType(BootstrapConsts.file_client_type);
        fileClient.download(response, code, name);
        return new ResponseResult().setSuccess(true).setMessage(ResultCode.SUCCESS.getMessage()).setCode(ResultCode.SUCCESS.getCode());
    }

    /** * Get the file extension *@return* /
    public static String getExtName(String filename) {
        int index = filename.lastIndexOf(".");

        if (index == -1) {
            return null;
        }
        String result = filename.substring(index);
        returnresult; }}Copy the code

The whole article is completely pure hand, if you feel helpful, remember to pay attention to praise yo ~~