这个region, accessKeyId,accessKeySecret,bucket是成员变量,建议写在配置文件中,注解注入。
@RequestMapping(value = "/pass/ossUploadTest.do", method = RequestMethod.POST) public @ResponseBody Map<String, Object> ossUploadTest(HttpServletRequest request, @RequestParam("file") CommonsMultipartFile file) throws Exception { // Endpoint以杭州为例,其它Region请按实际情况填写。 //String endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。 System.out.println(region); System.out.println(accessKeyId); System.out.println(accessKeySecret); System.out.println(bucket); String file_name = file.getOriginalFilename().trim(); String suffix = file_name.substring(file_name.lastIndexOf(".")); String fileName = System.currentTimeMillis() + suffix; System.out.println("filename:" + file_name); // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(region, accessKeyId, accessKeySecret); DiskFileItem fi = (DiskFileItem) file.getFileItem(); File resultFile = fi.getStoreLocation(); // 创建PutObjectRequest对象。 PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, resultFile);// 上传文件。 System.out.println("开始上传"); PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest); System.out.println("上传结束"); Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10); // 生成URL,第一个参数为bucketName,第二个参数key为上传的文件路径名称,第三个为过期时间 URL url = ossClient.generatePresignedUrl(bucket, fileName, expiration); //System.out.println(JSON.toJSONString(ossClient)); System.out.println("URL:" + url); // 关闭OSSClient。 ossClient.shutdown(); Map<String, Object> result = new HashMap<>(); result.put("success", true); result.put("data", url); result.put("msg", "成功"); return result; }
这是简单的上传文件的api,java中需要导入oss sdk所提供的相关的jar包。
访问阿里云官网:https://help.aliyun.com/document_detail/32009.html?spm=a2c4g.11186623.6.763.1568732033z2Y5