public List<String> uploadFile (@RequestPart(value = "file") MultipartFile[] file, @RequestParam(value = "pathKey") String pathKey) { List<String> urlArray = new ArrayList<String>(); if (file.length > 0) { if (StringUtils.isEmpty(pathKey)) { throw new RestException("pathKey cannot be null"); } for (MultipartFile multipartFile : file) { String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1); try { String tempUrl = aliyunOSSUtil.normalFileStreamUpload(multipartFile.getBytes(), pathKey, suffix); urlArray.add(tempUrl); } catch (IOException e) { e.printStackTrace(); } } } else { throw new RestException("上传文件不能为空"); } return urlArray; }
public String normalFileStreamUpload (byte[] data, String path) { // 创建OSSClient实例 OSS ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret); try (ByteArrayInputStream input=new ByteArrayInputStream(data)) { //校验Bucket if (ossClient.doesBucketExist(bucketName)) { } else { ossClient.createBucket(bucketName); } ossClient.putObject(bucketName, path, input); return domain + "/" + path; }catch (OSSException e) { e.printStackTrace(); } catch (ClientException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { // 关闭OSSClient ossClient.shutdown(); } return null; }
获取文件的外链 public String getOuterUrl(String pathKey) { OSSClient ossClient = new OSSClient(domain, accessKeyId,accessKeySecret); // 设置URL过期时间为12小时 Date expiration = new Date(new Date().getTime() + 12 * 3600 * 1000); GeneratePresignedUrlRequest generatePresignedUrlRequest ; generatePresignedUrlRequest =new GeneratePresignedUrlRequest(bucketName, pathKey); generatePresignedUrlRequest.setExpiration(expiration); URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest); return url.toString(); }
文件下载
public void fileDownload (String path, HttpServletResponse response) { String filePath = getOssKey(path); InputStream in = null; ServletOutputStream out = null; try { String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1); in = this.fileDownload(fileName); if (in==null){ throw new RestException(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMsg()); } response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName.split("/")[2], "UTF-8")); out = response.getOutputStream(); byte[] data = new byte[1024]; boolean var8 = false; int len; while((len = in.read(data)) != -1) { out.write(data, 0, len); } out.flush(); } catch (Exception e) { logger.info(Logger.EVENT_SUCCESS, "AliyunOSS fileDownload(String path, HttpServletResponse response) failed"); e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception var15) { var15.printStackTrace(); } } }