当前位置:   article > 正文

阿里云文件上传与删除_aliyunupload.vod

aliyunupload.vod

前言

  • Java开发中将本地文件上传至阿里云服务器上

代码实现

1.Controller接口实现

@RestController
@RequestMapping("/help")
public class UploadAliyunController {

    private final static Logger LOG = LoggerFactory.getLogger(UploadAliyunController.class);

    /**
     * @return
     * @function 视频上传
     */
    @PostMapping("uploadVideo")
    public Map uploadVideo(@RequestHeader(value = "lid") String lid,@RequestParam(value = "file") MultipartFile file) {
        if (StringUtils.isBlank(file.getOriginalFilename())) {
            //return R.error(500, "内容为空");
            throw new RRException("请上传视频", 10001);
        }
        String fileName = file.getOriginalFilename();
        fileName = fileName.substring(fileName.lastIndexOf(".") + 1);
        //&& !"webm".equals(fileName) && !"ogg".equals(fileName)
        if (!"mp4".equals(fileName) ) {
            throw new RRException("上传视频格式不正确!", 10003);
        }
        if (file.getSize() >= 1073741824) {
            throw new RRException("文件不要超过1G", 10005);
        }
        String videoUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_VIDEO);
        if (StringUtils.isBlank(videoUrl)){
            Map map = new HashMap();
            map.put("code", 1);//0表示成功,1失败
            map.put("msg", "上传失败");//提示消息
            map.put("coverURL", videoUrl);//图片url
            Map<String, Object> Imgmap = new HashMap<>();
            Imgmap.put("src", videoUrl);//图片url
            Imgmap.put("title", file.getOriginalFilename());//图片名称
            map.put("data", Imgmap);
            return map;
        }
        Map map = new HashMap();
        map.put("code", 0);//0表示成功,1失败
        map.put("msg", "上传成功");//提示消息
        //map.put("imgUrl", imgUrl);//图片url
        map.put("coverURL", videoUrl);//图片url
        Map<String, Object> Imgmap = new HashMap<>();
        Imgmap.put("src", videoUrl);//图片url
        Imgmap.put("title", file.getOriginalFilename());//图片名称
        map.put("data", Imgmap);
        return map;
    }

    /**
     * @param file
     * @return
     * @function 图片上传
     */
    @PostMapping("uploadImage")
    public Map uploadImages(@RequestHeader(value = "lid") String lid,@RequestParam(value = "file") MultipartFile file) {
        if (StringUtils.isBlank(file.getOriginalFilename())) {
            throw new RRException("请选择上传的图片", 10001);
        }
        String fileName = file.getOriginalFilename();
        fileName = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (!"png".equals(fileName) && !"jpg".equals(fileName) && !"jpeg".equals(fileName) && !"gif".equals(fileName)) {
            throw new RRException("上传图片的格式不正确", 10002);
        }
        if (file.getSize() >= 5242880) {
            throw new RRException("图片大小超过5M", 10005);
        }
        String imgUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES);
        if (StringUtils.isBlank(imgUrl)){
            Map map = new HashMap();
            map.put("code", 302);//0表示成功,1失败
            map.put("msg", "上传失败");//提示消息
            Map<String, Object> Imgmap = new HashMap<>();
            Imgmap.put("src", imgUrl);//图片url
            Imgmap.put("title", file.getOriginalFilename());//图片名称
            map.put("data", Imgmap);
            return map;
        }
        Map map = new HashMap();
        map.put("code", 200);
        map.put("msg", "上传成功");//提示消息
        Map<String, Object> Imgmap = new HashMap<>();
        Imgmap.put("src", imgUrl);//图片url
        Imgmap.put("title", file.getOriginalFilename());//图片名称
        map.put("data", Imgmap);
        return map;
    }

    /**
     * @param file
     * @return
     * @function 文件上传
     */
    @PostMapping("uploadFile")
    public Map uploadFile(@RequestHeader(value = "lid") String lid,@RequestParam(value = "file") MultipartFile file) {
        if (StringUtils.isBlank(file.getOriginalFilename())) {
            throw new RRException("请选择上传文件", 10001);
        }
        String fileName = file.getOriginalFilename();
        fileName = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (!"jpg".equals(fileName) && !"png".equals(fileName) && !"jpeg".equals(fileName) && !"gif".equals(fileName) && !"doc".equals(fileName) && !"docx".equals(fileName) && !"pdf".equals(fileName)) {
            throw new RRException("文件格式不正确", 10002);
        }
        if (file.getSize() >= 5242880) {
            throw new RRException("文件大小超过5M", 10005);
        }
        String fileUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_FILE);
        Map<String, Object> Imgmap = new HashMap<>();
        Imgmap.put("url", fileUrl);//图片url
        Imgmap.put("fileName", file.getOriginalFilename());//图片名称
        if (StringUtils.isBlank(fileUrl)){
            return R.error("上传失败").put("results",Imgmap);
        }
        return R.ok().put("results",Imgmap);
    }

    @GetMapping("delUpload")
    @ApiOperation("删除上传文件")
    public R delUpload(@RequestHeader(value = "lid") String lid,@RequestParam(value = "url") String fileName) {
        if (StringUtils.isBlank(fileName)) {
            throw new RRException("请选择删除文件", 10001);
        }
        Boolean result = OssUtil.deleteOne(fileName);
        if (result) {
            return R.ok("删除成功");
        } else {
            throw new RRException("删除失败,文件不存在");
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130

2.yml配置
yml配置
3.阿里云上传相关工具类

public class OssUtil {

    private static final String PROPETIES_PATH = "application.yml";
    private static final Properties PROP = PropertiesUtils.getProperties(PROPETIES_PATH);

    private final static Logger LOG = LoggerFactory.getLogger(OssUtil.class);

    /**
     * 域名
     */
    private final static String OSS_END_POINT = PROP.getProperty("ossendpoint");

    /**
     * 账号
     */
    private final static String OSS_ACCESS_KEY_ID = PROP.getProperty("ossaccesskeyid");

    /**
     * 密匙
     */
    private final static String OSS_ACCESS_KEY_SECRET = PROP.getProperty("ossaccesskeysecet");

    /**
     * 存储空间
     */
    private final static String OSS_BUCKET_NAME = PROP.getProperty("ossbucketname");


    /**
     * URL有效期
     */
    private final static Date OSS_URL_EXPIRATION = DateUtils.addDays(new Date(), 365 * 10);


    private volatile static OSS instance = null;

    private OssUtil() {
    }

    /**
     * Oss 实例化
     *
     * @return
     */
    private static OSS getOssClient() {
        if (instance == null) {
            synchronized (OssUtil.class) {
                if (instance == null) {
                    instance = new OSSClientBuilder().build(OSS_END_POINT, OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET);
                }
            }
        }
        return instance;
    }

    private static void colseOssClient() {
        if (OssUtil.getOssClient() != null) {
            OssUtil.getOssClient().shutdown();
        }
    }

    /**
     * 文件路径的枚举
     */
    public enum FileDirType {
        ARTICLE_IMAGES("help_images"), ARTICLE_VIDEO("help_video"), ARTICLE_FILE("help_file"), CAROUSEL("carousel"), MENU("menu");
        private String dir;

        FileDirType(String dir) {
            this.dir = dir;
        }

        @JsonValue
        public String getDir() {
            return dir;
        }
    }

    /**
     * 当Bucket 不存在时候创建Bucket
     */
    private static void createBuchet() {
        try {
            if (!OssUtil.getOssClient().doesBucketExist(OSS_BUCKET_NAME)) {
                OssUtil.getOssClient().createBucket(OSS_BUCKET_NAME);
            }
        } catch (Exception e) {
            LOG.warn("创建BUCHET失败:", e);
            throw new ClientException("创建Bucket失败,请核对Bucket名称(规则:只能包含小写字母、数字和短横线,必须以小写字母和数字开头和结尾,长度在3-63之间)");
        }
    }


    /**
     * 文件上传的文件后缀
     *
     * @param filenameExtension
     * @return
     */
    private static String getContentType(String filenameExtension) {
        String type = null;
        switch (filenameExtension) {
            case "jpeg":
            case "jpg":
                type = "image/jpeg";
                break;
            case "png":
                type = "image/png";
                break;
            case "gif":
                type = "image/gif";
                break;
            case "pdf":
                type = "application/pdf";
                break;
            case "doc":
            case "docx":
                type = "application/msword";
                break;
            case "mp4":
                type = "video/mpeg4";
                break;
            default:
                type = filenameExtension;
                break;
        }
        return type;
    }


    /**
     * 上传OSS服务器 如果同名文件会覆盖服务器上的
     * jdk1.7新特性的书写方式:try-with-resource,可以实现自动关流操作
     * @param file
     * @param fileDirType
     * @return
     */
    private static String uploadFile(MultipartFile file, FileDirType fileDirType) {
        String fileName = String.format("%s.%s", UUID.randomUUID().toString(), FilenameUtils.getExtension(file.getOriginalFilename()));
        try (InputStream inputStream = file.getInputStream()) {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getContentType(FilenameUtils.getExtension("." + file.getOriginalFilename())));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //校验MD5
            objectMetadata.setContentMD5(BinaryUtil.toBase64String(BinaryUtil.calculateMd5(file.getBytes())));
            PutObjectResult putObjectResult = OssUtil.getOssClient().putObject(OSS_BUCKET_NAME, fileDirType.getDir() + "/" + fileName, inputStream, objectMetadata);
            LOG.info("成功之putObjectResult:" + putObjectResult);
            return fileDirType.getDir() + "/" + fileName;
        } catch (OSSException oe) {
            LOG.warn("上传文件之OSSException异常:", oe);
            LOG.warn("Error Message: " + oe.getErrorCode());
            LOG.warn("Error Code:    " + oe.getErrorCode());
            LOG.warn("Request ID:    " + oe.getRequestId());
            LOG.warn("Host ID:       " + oe.getHostId());
            return null;
        } catch (ClientException ce) {
            LOG.warn("上传文件之ClientException异常:", ce);
            LOG.warn("Error Message: " + ce.getMessage());
            return null;
        } catch (IOException e) {
            LOG.warn("上传文件之IOException异常:", e);
            LOG.warn("Error Message: " + e.getMessage());
            return null;
        }
    }

    /**
     * 获取文件路径
     *
     * @param fileUrl
     * @param fileDirType
     * @return
     */
    private static String getFileUrl(String fileUrl, FileDirType fileDirType) {
        if (StringUtils.isEmpty(fileUrl)) {
            throw new RuntimeException("文件地址为空!");
        }
        String[] split = fileUrl.split("/");
        URL url = OssUtil.getOssClient().generatePresignedUrl(OSS_BUCKET_NAME, fileDirType.getDir() + "/" + split[split.length - 1], OSS_URL_EXPIRATION);
        if (url == null) {
            throw new RuntimeException("获取OSS文件URL失败!");
        }
        return url.toString();
    }

    /**
     * 文件上传 去掉URL中的?后的时间戳
     * 设置成公共的独写,把问号后面的东西给截取掉
     * @param file
     * @param fileDirType
     * @return
     */
    public static String upload(MultipartFile file, FileDirType fileDirType) {
        OssUtil.createBuchet();
        String fileName = OssUtil.uploadFile(file, fileDirType);
        if (StringUtils.isBlank(fileName)) {
            return null;
        }
        String fileOssUrl = OssUtil.getFileUrl(fileName, fileDirType);
        int firstChar = fileOssUrl.indexOf("?");
        if (firstChar > 0) {
            fileOssUrl = fileOssUrl.substring(0, firstChar);
        }
        return fileOssUrl;
    }


    /**
     * 获取路径地址
     *
     * @param fileName
     * @return
     */
    public static String getPathUrl(String fileName) {
        return fileName.substring(fileName.indexOf(OSS_END_POINT) + OSS_END_POINT.length() + 1);
    }


    /**
     * 文件删除,删除集合
     *
     * @param keys
     */
    public static void delete(List<String> keys) {
        List<String> newKeys = keys.stream().map((item) -> {
            return OssUtil.getPathUrl(item);
        }).collect(Collectors.toList());
        try {
            DeleteObjectsResult deleteObjectsResult = OssUtil.getOssClient().deleteObjects(new DeleteObjectsRequest(OSS_BUCKET_NAME).withKeys(newKeys));
            List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
            System.out.println(deletedObjects);
        } catch (OSSException oe) {
            LOG.warn("批量删除之OSSException异常:", oe);
            LOG.warn("Error Message: " + oe.getErrorCode());
            LOG.warn("Error Code:    " + oe.getErrorCode());
            LOG.warn("Request ID:    " + oe.getRequestId());
            LOG.warn("Host ID:       " + oe.getHostId());
        } catch (ClientException ce) {
            LOG.warn("批量删除之ClientException异常:", ce);
            LOG.warn("Error Message: " + ce.getMessage());
        }

    }

    /**
     * 获取文件名字
     *
     * @return
     */
    public static String getFileName(String filename) {
        String file = "";

        if (filename.contains(FileDirType.ARTICLE_IMAGES.getDir())) {
            file = FileDirType.ARTICLE_IMAGES.getDir();
        } else if (filename.contains(FileDirType.ARTICLE_VIDEO.getDir())) {
            file = FileDirType.ARTICLE_VIDEO.getDir();
        } else {
            file = FileDirType.ARTICLE_FILE.getDir();
        }
        int firstChar = filename.indexOf("?");
        if (firstChar > 0) {
            filename = filename.substring(0, firstChar);
        }
        filename = file + filename.substring(filename.lastIndexOf("/"));
        return filename;
    }


    public static boolean deleteOne(String filename) {
        filename = OssUtil.getFileName(filename);
        boolean found = OssUtil.getOssClient().doesObjectExist(OSS_BUCKET_NAME, filename);
        if (found) {
            // 删除文件。如需删除文件夹,请将ObjectName设置为对应的文件夹名称。如果文件夹非空,则需要将文件夹下的所有object删除后才能删除该文件夹。
            OssUtil.getOssClient().deleteObject(OSS_BUCKET_NAME, filename);
            return true;
        }
        return false;
    }
}

/**
 * 自定义异常类
 *
 * *
 */
public class RRException extends RuntimeException {
	private static final long serialVersionUID = 1L;
	
    private String msg;
    private int code = 500;
    
    public RRException(String msg) {
		super(msg);
		this.msg = msg;
	}
	
	public RRException(String msg, Throwable e) {
		super(msg, e);
		this.msg = msg;
	}
	
	public RRException(String msg, int code) {
		super(msg);
		this.msg = msg;
		this.code = code;
	}

	public RRException(String msg, int code, Throwable e) {
		super(msg, e);
		this.msg = msg;
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}
}

/**
 * @author jwang properties文件读写工具类
 *
 */
public abstract class PropertiesUtils {
	private final static Logger LOG = LoggerFactory.getLogger(PropertiesUtils.class);

	public static Properties getProperties(String path) {
		Properties prop = new Properties();

		loadProp(prop, path);

		return prop;
	}

	private static void loadProp(Properties p, String conf) {
		InputStream is = getInputStream(conf);
		if (null != is) {
			try {
				p.load(is);
			} catch (IOException e) {
				LOG.info("file not found!");
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						LOG.info("stream close fail!");
					}
				}
			}
		}
	}

	// 获取输入流
	private static InputStream getInputStream(String conf) {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

		InputStream is = null;

		if (null != classLoader) {
			is = classLoader.getResourceAsStream(conf);
		}
		return is;
	}

	// 获取输出流
	private static OutputStream getOutPutStream(String conf) {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

		OutputStream out = null;

		if (null != classLoader) {
			String filePath = classLoader.getResource(conf).getFile();
			try {
				out = new FileOutputStream(filePath);
			} catch (FileNotFoundException e) {
				LOG.info("file not found!!!");
			}
		}
		return out;
	}

	// 读取key=value
	public static String getValue(Properties p, String key) {
		String value = p.getProperty(key);
		return value == null ? "" : value;
	}

	// 设置key=value
	public static void setValue(String conf, String key, String value) {
		Properties p = getProperties(conf);
		OutputStream out = getOutPutStream(conf);
		p.setProperty(key, value);
		try {
			p.store(out, "set:" + key + "=" + value);
		} catch (IOException e) {
			LOG.info("set properties fail!!!");
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					LOG.info("stream close fail!");
				}
			}
		}
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
  • 411
  • 412
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418
  • 419
  • 420
  • 421
  • 422
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/245980
推荐阅读
相关标签
  

闽ICP备14008679号