上传文件至阿里云

1. 添加jar包

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>2.8.3</version>
</dependency>

2. 代码实现

@RequestMapping(value="addImg",method=RequestMethod.POST)//
		public String addForums( @RequestParam MultipartFile myfile,HttpServletRequest request,HttpSession session){
			
			// endpoint以杭州为例,其它region请按实际情况填写。
			String endpoint = "https://oss-cn-shanghai.aliyuncs.com";
			// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
			String accessKeyId = "xxxxxxxxxxx";
			String accessKeySecret ="xxxxxxxxxxxxxxxxxxxx";
			// 创建OSSClient实例。
			OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			
			// 上传文件流。
			InputStream inputStream=null;
			try {
				if (!myfile.isEmpty()) {
					
					inputStream = myfile.getInputStream();
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ossClient.putObject("hlww", "hlww/news/news_img/111.jpeg", inputStream);

			// 关闭ossClient。
			ossClient.shutdown();
			//-------end-------
			return "xxx/xxx/xx";
		}

  3. 可能出现问题

    3.1 jar包兼容性问题,高低版本的jar包,将低版本删除。

    3.2 前端的上传accessKeyId, accessKeySecret 是不固定的,要访问后台接口获取;后台是固定的,在阿里云上添加。

原文地址:https://www.cnblogs.com/dztHome/p/9171509.html