Java Code Examples for com.aliyun.oss.OSSClient#putObject()

The following examples show how to use com.aliyun.oss.OSSClient#putObject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AliyunOSSTest.java    From mblog with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
    // Endpoint以杭州为例,其它Region请按实际情况填写。
    String endpoint = "oss-cn-beijing.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
    String accessKeyId = "";
    String accessKeySecret = "";
    String bucketName = "mtons";

    File file = new File("F:/data/a_2.jpg");
    byte[] bytes = ImageUtils.screenshot(file, 360, 200);
    String key = UpYunUtils.md5(bytes);

    // 创建OSSClient实例。
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

    // 上传内容到指定的存储空间(bucketName)并保存为指定的文件名称(objectName)。
    PutObjectResult result = ossClient.putObject(bucketName, "static/"+key + ".jpg", new ByteArrayInputStream(bytes));

    // 关闭OSSClient。
    ossClient.shutdown();
}
 
Example 2
Source File: TestOSSService.java    From jframe with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws OSSException, ClientException, IOException {
    OSSClient client = new OSSClient("oss-cn-hangzhou.aliyuncs.com", "", "", "");
    // BucketInfo info = client.getBucketInfo("edrmry");
    boolean exists = client.doesBucketExist("edrmry");
    System.out.println(exists);
    // System.out.println(client.listBuckets().size());
    // client.createBucket("dzh1");
    PutObjectResult r = client.putObject("edrmry", "dzh1.jpg", new FileInputStream("/Users/dzh/Pictures/8.pic.jpg"));
    System.out.println(r.getETag());
    OSSObject o = client.getObject("edrmry", "dzh1");
    InputStream is = o.getObjectContent();

    FileOutputStream fos = new FileOutputStream("/Users/dzh/Pictures/8.pic.2.jpg");
    int len = 0;
    byte[] buf = new byte[32];
    while ((len = is.read(buf)) != -1) {
        fos.write(buf, 0, len);
    }
    fos.flush();
    fos.close();
}
 
Example 3
Source File: OSSUploadTest.java    From cms with Apache License 2.0 6 votes vote down vote up
@Test
	public void upload(){
		OSSClient client=OSSClientFactory.create();
		
		String bucketName="b-cdn";
		String path="/opt/001.jpg";
		PutObjectResult result=client.putObject(bucketName, "cms"+path, new File(path));
		JSONObject json = JSONObject.fromObject(result);
		
		System.out.println(json.toString());
		
		// 列举bucket
//		List<Bucket> buckets = client.listBuckets();
//		for (Bucket bucket : buckets) {
//		    System.out.println(" - " + bucket.getName());
//		}
		
		
		client.shutdown();
	}
 
Example 4
Source File: AliyunOSSClientUtil.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 创建模拟文件夹
 *
 * @param ossClient  oss连接
 * @param bucketName 存储空间
 * @param folder     模拟文件夹名如"qj_nanjing/"
 * @return 文件夹名
 */
public static String createFolder(OSSClient ossClient, String bucketName, String folder) {
    //文件夹名
    final String keySuffixWithSlash = folder;
    //判断文件夹是否存在,不存在则创建
    if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
        //创建文件夹
        ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
        logger.info("创建文件夹成功");
        //得到文件夹名
        OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
        String fileDir = object.getKey();
        return fileDir;
    }
    return keySuffixWithSlash;
}
 
Example 5
Source File: AliFileManage.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
@Override
public String inputStreamUpload(InputStream inputStream, String key, MultipartFile file) {

    OssSetting os = getOssSetting();
    OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), new DefaultCredentialProvider(os.getAccessKey(), os.getSecretKey()), null);
    ossClient.putObject(os.getBucket(), key, inputStream);
    ossClient.shutdown();
    return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + key;
}
 
Example 6
Source File: AliyunStorageImpl.java    From mblog with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String writeToStore(byte[] bytes, String pathAndFileName) throws Exception {
    String endpoint = options.getValue(oss_endpoint);
    String bucket = options.getValue(oss_bucket);
    String src = options.getValue(oss_src);

    if (StringUtils.isAnyBlank(endpoint, bucket)) {
        throw new MtonsException("请先在后台设置阿里云配置信息");
    }

    if (StringUtils.isBlank(src)) {
        src = "";
    } else {
        if (src.startsWith("/")) {
            src = src.substring(1);
        }

        if (!src.endsWith("/")) {
            src = src + "/";
        }
    }

    String key = UpYunUtils.md5(bytes);
    String path = src + key + FileKit.getSuffix(pathAndFileName);
    OSSClient client = builder();
    client.putObject(bucket, path, new ByteArrayInputStream(bytes));
    return "//" + bucket.trim() + "." + endpoint.trim() + "/" + path;
}
 
Example 7
Source File: OssUploadServiceImpl.java    From mysiteforme with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean testAccess(UploadInfo uploadInfo) {
    ClassPathResource classPathResource = new ClassPathResource("static/images/userface1.jpg");
    try {
        OSSClient ossClient = new OSSClient(uploadInfo.getOssEndpoint(),uploadInfo.getOssKeyId(), uploadInfo.getOssKeySecret());
        InputStream inputStream = classPathResource .getInputStream();
        ossClient.putObject(uploadInfo.getOssBucketName(), "test.jpg", inputStream, null);
        ossClient.shutdown();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 8
Source File: AliyunUtil.java    From roncoo-education with MIT License 5 votes vote down vote up
/**
 * 文件存储入OSS
 * 
 * @param bucketName
 * @param key
 * @param inputStream
 */
private static PutObjectResult putObjectForFile(String endpoint, String keyId, String keySecret, String bucketName, String key, InputStream inputStream, String fileName) {
	OSSClient ossClient = getOssClient(endpoint, keyId, keySecret);
	ObjectMetadata meta = new ObjectMetadata();
	if (StringUtils.isNotBlank(fileName)) {
		meta.setContentDisposition("attachment;filename={}".replace("{}", fileName));
		meta.setObjectAcl(CannedAccessControlList.Private);
	}
	return ossClient.putObject(bucketName, key, inputStream, meta);
}
 
Example 9
Source File: ApiBootOssService.java    From api-boot with Apache License 2.0 5 votes vote down vote up
@Override
public ApiBootObjectStorageResponse upload(String objectName, String localFile) throws ApiBootObjectStorageException {
    try {
        OSSClient ossClient = getOssClient();
        // put byte inputStream
        ossClient.putObject(new PutObjectRequest(bucketName, objectName, new File(localFile)).withProgressListener(new OssProgressListener(objectName, apiBootObjectStorageProgress)));
        closeOssClient(ossClient);
    } catch (Exception e) {
        throw new ApiBootObjectStorageException(e.getMessage(), e);
    }
    return ApiBootObjectStorageResponse.builder().objectName(objectName).objectUrl(getObjectUrl(objectName)).build();
}
 
Example 10
Source File: ApiBootOssService.java    From api-boot with Apache License 2.0 5 votes vote down vote up
@Override
public ApiBootObjectStorageResponse upload(String objectName, InputStream inputStream) throws ApiBootObjectStorageException {
    try {
        OSSClient ossClient = getOssClient();
        // put byte inputStream
        ossClient.putObject(new PutObjectRequest(bucketName, objectName, inputStream).withProgressListener(new OssProgressListener(objectName, apiBootObjectStorageProgress)));
        closeOssClient(ossClient);
    } catch (Exception e) {
        throw new ApiBootObjectStorageException(e.getMessage(), e);
    }
    return ApiBootObjectStorageResponse.builder().objectName(objectName).objectUrl(getObjectUrl(objectName)).build();
}
 
Example 11
Source File: ApiBootOssService.java    From api-boot with Apache License 2.0 5 votes vote down vote up
@Override
public ApiBootObjectStorageResponse upload(String objectName, byte[] bytes) throws ApiBootObjectStorageException {
    try {
        OSSClient ossClient = getOssClient();
        // put byte inputStream
        ossClient.putObject(new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(bytes)).withProgressListener(new OssProgressListener(objectName, apiBootObjectStorageProgress)));
        closeOssClient(ossClient);
    } catch (Exception e) {
        throw new ApiBootObjectStorageException(e.getMessage(), e);
    }
    return ApiBootObjectStorageResponse.builder().objectName(objectName).objectUrl(getObjectUrl(objectName)).build();
}
 
Example 12
Source File: AliOssStorage.java    From springboot-learn with MIT License 5 votes vote down vote up
public void upload() {

        if (StringUtils.isAnyBlank(accessKeyId, accessKeySecret, endpoint, bucketName)) {
            throw new IllegalArgumentException("请先设置配置信息");
        }

        //文件所在的目录名
        String fileDir = "link/";
        //文件名
        String key = "aliU.png";
        String path = fileDir + key;
        File file = null;
        try {
            //此处的static前不能加/!!!
            file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/images/user.png");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        // 上传内容到指定的存储空间(bucketName)并保存为指定的文件名称(objectName)。
        PutObjectResult putObjectResult = ossClient.putObject(bucketName, path, file);

        // 关闭OSSClient。
        ossClient.shutdown();

        System.out.println("访问路径=====》" + endpoint + "/" + path);

    }
 
Example 13
Source File: AliFileManage.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
@Override
public String pathUpload(String filePath, String key) {

    OssSetting os = getOssSetting();
    OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), new DefaultCredentialProvider(os.getAccessKey(), os.getSecretKey()), null);
    ossClient.putObject(os.getBucket(), key, new File(filePath));
    ossClient.shutdown();
    return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + key;
}
 
Example 14
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@RequiresPermissions("common:upload:oss:base64")
@RequestMapping(value = "/oss/base64", method = RequestMethod.POST)
@ResponseBody
@AccessLog(module = AdminModule.COMMON, operation = "base64上传oss")
public MessageResult base64UpLoad(@RequestParam String base64Data) {
    MessageResult result = new MessageResult();
    try {
        logger.debug("上传文件的数据:" + base64Data);
        String dataPrix = "";
        String data = "";

        logger.debug("对数据进行判断");
        if (base64Data == null || "".equals(base64Data)) {
            throw new Exception("上传失败,上传图片数据为空");
        } else {
            String[] d = base64Data.split("base64,");
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                throw new Exception("上传失败,数据不合法");
            }
        }

        logger.debug("对数据进行解析,获取文件名和流数据");
        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {//data:image/jpeg;base64,base64编码的jpeg图片数据
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {//data:image/x-icon;base64,base64编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {//data:image/gif;base64,base64编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {//data:image/png;base64,base64编码的png图片数据
            suffix = ".png";
        } else {
            throw new Exception("上传图片格式不合法");
        }
        String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
        String key = directory + GeneratorUtil.getUUID() + suffix;

        //因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
        byte[] bs = Base64Utils.decodeFromString(data);
        OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
        try {
            //使用apache提供的工具类操作流
            InputStream is = new ByteArrayInputStream(bs);
            //FileUtils.writeByteArrayToFile(new File(Global.getConfig(UPLOAD_FILE_PAHT), tempFileName), bs);
            ossClient.putObject(aliyunConfig.getOssBucketName(), key, is);
            String uri = aliyunConfig.toUrl(key);
            MessageResult mr = new MessageResult(0, "上传成功");
            mr.setData(uri);
            logger.debug("上传成功,key:{}", key);
            return mr;
        } catch (Exception ee) {
            throw new Exception("上传失败,写入文件失败," + ee.getMessage());
        }
    } catch (Exception e) {
        logger.debug("上传失败," + e.getMessage());
        result.setCode(500);
        result.setMessage("上传失败," + e.getMessage());
    }
    return result;
}
 
Example 15
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@RequestMapping(value = "/oss/image", method = RequestMethod.POST)
@ResponseBody
@AccessLog(module = AdminModule.COMMON, operation = "上传oss图片")
public String uploadOssImage(
        HttpServletRequest request,
        HttpServletResponse response,
        @RequestParam("file") MultipartFile file) throws IOException {
    log.info(request.getSession().getServletContext().getResource("/"));
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    if (!ServletFileUpload.isMultipartContent(request)) {
        return MessageResult.error(500, sourceService.getMessage("FORMAT_NOT_SUPPORTED")).toString();
    }
    if (file == null) {
        return MessageResult.error(500, sourceService.getMessage("FILE_NOT_FOUND")).toString();
    }

    String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());

    OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
    try {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String key = directory + GeneratorUtil.getUUID() + suffix;
        System.out.println(key);
        ossClient.putObject(aliyunConfig.getOssBucketName(), key, file.getInputStream());
        String uri = aliyunConfig.toUrl(key);
        MessageResult mr = new MessageResult(0, sourceService.getMessage("SUCCESS"));
        mr.setData(uri);
        return mr.toString();
    } catch (OSSException oe) {
        return MessageResult.error(500, oe.getErrorMessage()).toString();
    } catch (ClientException ce) {
        System.out.println("Error Message: " + ce.getMessage());
        return MessageResult.error(500, ce.getErrorMessage()).toString();
    } catch (Throwable e) {
        e.printStackTrace();
        return MessageResult.error(500, sourceService.getMessage("REQUEST_FAILED")).toString();
    } finally {
        ossClient.shutdown();
    }
}
 
Example 16
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
 * 上传base64处理后的图片
 *
 * @param base64Data
 * @return
 */
@RequestMapping(value = "/upload/oss/base64", method = RequestMethod.POST)
@ResponseBody
public MessageResult base64UpLoad(@RequestParam String base64Data) {
    MessageResult result = new MessageResult();
    try {
        log.debug("上传文件的数据:" + base64Data);
        String dataPrix = "";
        String data = "";
        if (base64Data == null || "".equals(base64Data)) {
            throw new Exception(sourceService.getMessage("NOT_FIND_FILE"));
        } else {
            String[] d = base64Data.split("base64,");
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                throw new Exception(sourceService.getMessage("DATA_ILLEGAL"));
            }
        }
        log.debug("对数据进行解析,获取文件名和流数据");
        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {//data:image/jpeg;base64,base64编码的jpeg图片数据
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {//data:image/x-icon;base64,base64编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {//data:image/gif;base64,base64编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {//data:image/png;base64,base64编码的png图片数据
            suffix = ".png";
        } else {
            throw new Exception(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
        String key = directory + GeneratorUtil.getUUID() + suffix;

        //因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
        byte[] bs = Base64Utils.decodeFromString(data);
        OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
        try {
            //使用apache提供的工具类操作流
            InputStream is = new ByteArrayInputStream(bs);
            //FileUtils.writeByteArrayToFile(new File(Global.getConfig(UPLOAD_FILE_PAHT), tempFileName), bs);
            ossClient.putObject(aliyunConfig.getOssBucketName(), key, is);
            String uri = aliyunConfig.toUrl(key);
            MessageResult mr = new MessageResult(0, sourceService.getMessage("UPLOAD_SUCCESS"));
            mr.setData(uri);
            mr.setMessage(sourceService.getMessage("UPLOAD_SUCCESS"));
            log.debug("上传成功,key:{}", key);
            return mr;
        } catch (Exception ee) {
            log.info(ee.getMessage());
            throw new Exception(sourceService.getMessage("FAILED_TO_WRITE"));
        }
    } catch (Exception e) {
        log.debug("上传失败," + e.getMessage());
        result.setCode(500);
        result.setMessage(e.getMessage());
    }
    return result;
}
 
Example 17
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
 * 上传图片到阿里云OSS
 *
 * @param request
 * @param response
 * @param file
 * @return
 * @throws IOException
 */
@RequestMapping(value = "upload/oss/image", method = RequestMethod.POST)
@ResponseBody
public MessageResult uploadOssImage(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam("file") MultipartFile file) throws IOException {
    log.info(request.getSession().getServletContext().getResource("/").toString());
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    Assert.isTrue(ServletFileUpload.isMultipartContent(request), sourceService.getMessage("FORM_FORMAT_ERROR"));
    Assert.isTrue(file != null, sourceService.getMessage("NOT_FIND_FILE"));
    log.info("该文件的文件流为转为类型>>>>>>>>>>>"+UploadFileUtil.getFileHeader(file.getInputStream()));
    String fileType=UploadFileUtil.getFileType(file.getInputStream());
    System.out.println("fileType="+fileType);
    String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
    OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
    try {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        System.out.println("suffix="+suffix);
        if (!allowedFormat.contains(suffix.trim().toLowerCase())) {
            return MessageResult.error(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        if(fileType==null||!allowedFormat.contains(fileType.trim().toLowerCase())){
            return MessageResult.error(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        String key = directory + GeneratorUtil.getUUID() + suffix;
        System.out.println(key);
        //压缩文件
        String path = request.getSession().getServletContext().getRealPath("/") + "upload/"+file.getOriginalFilename();
        File tempFile=new File(path);
        FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
        log.info("=================压缩前"+tempFile.length());
        UploadFileUtil.zipWidthHeightImageFile(tempFile,tempFile,425,638,0.7f);
        log.info("=================压缩后"+tempFile.length());
        ossClient.putObject(aliyunConfig.getOssBucketName(), key, file.getInputStream());
        String uri = aliyunConfig.toUrl(key);
        log.info(">>>>>>>>>>上传成功>>>>>>>>>>>>>");
        MessageResult mr = new MessageResult(0, sourceService.getMessage("UPLOAD_SUCCESS"));
        mr.setData(uri);
        return mr;
    } catch (OSSException oe) {
        return MessageResult.error(500, oe.getErrorMessage());
    } catch (ClientException ce) {
        System.out.println("Error Message: " + ce.getMessage());
        return MessageResult.error(500, ce.getErrorMessage());
    } catch (Throwable e) {
        e.printStackTrace();
        return MessageResult.error(500, sourceService.getMessage("SYSTEM_ERROR"));
    } finally {
        ossClient.shutdown();
    }
}
 
Example 18
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@RequiresPermissions("common:upload:oss:base64")
@RequestMapping(value = "/oss/base64", method = RequestMethod.POST)
@ResponseBody
@AccessLog(module = AdminModule.COMMON, operation = "base64上传oss")
public MessageResult base64UpLoad(@RequestParam String base64Data) {
    MessageResult result = new MessageResult();
    try {
        logger.debug("上传文件的数据:" + base64Data);
        String dataPrix = "";
        String data = "";

        logger.debug("对数据进行判断");
        if (base64Data == null || "".equals(base64Data)) {
            throw new Exception("上传失败,上传图片数据为空");
        } else {
            String[] d = base64Data.split("base64,");
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                throw new Exception("上传失败,数据不合法");
            }
        }

        logger.debug("对数据进行解析,获取文件名和流数据");
        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {//data:image/jpeg;base64,base64编码的jpeg图片数据
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {//data:image/x-icon;base64,base64编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {//data:image/gif;base64,base64编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {//data:image/png;base64,base64编码的png图片数据
            suffix = ".png";
        } else {
            throw new Exception("上传图片格式不合法");
        }
        String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
        String key = directory + GeneratorUtil.getUUID() + suffix;

        //因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
        byte[] bs = Base64Utils.decodeFromString(data);
        OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
        try {
            //使用apache提供的工具类操作流
            InputStream is = new ByteArrayInputStream(bs);
            //FileUtils.writeByteArrayToFile(new File(Global.getConfig(UPLOAD_FILE_PAHT), tempFileName), bs);
            ossClient.putObject(aliyunConfig.getOssBucketName(), key, is);
            String uri = aliyunConfig.toUrl(key);
            MessageResult mr = new MessageResult(0, "上传成功");
            mr.setData(uri);
            logger.debug("上传成功,key:{}", key);
            return mr;
        } catch (Exception ee) {
            throw new Exception("上传失败,写入文件失败," + ee.getMessage());
        }
    } catch (Exception e) {
        logger.debug("上传失败," + e.getMessage());
        result.setCode(500);
        result.setMessage("上传失败," + e.getMessage());
    }
    return result;
}
 
Example 19
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@RequestMapping(value = "/oss/image", method = RequestMethod.POST)
@ResponseBody
@AccessLog(module = AdminModule.COMMON, operation = "上传oss图片")
public String uploadOssImage(
        HttpServletRequest request,
        HttpServletResponse response,
        @RequestParam("file") MultipartFile file) throws IOException {
    log.info(request.getSession().getServletContext().getResource("/"));
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    if (!ServletFileUpload.isMultipartContent(request)) {
        return MessageResult.error(500, sourceService.getMessage("FORMAT_NOT_SUPPORTED")).toString();
    }
    if (file == null) {
        return MessageResult.error(500, sourceService.getMessage("FILE_NOT_FOUND")).toString();
    }

    String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());

    OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
    try {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String key = directory + GeneratorUtil.getUUID() + suffix;
        System.out.println(key);
        ossClient.putObject(aliyunConfig.getOssBucketName(), key, file.getInputStream());
        String uri = aliyunConfig.toUrl(key);
        MessageResult mr = new MessageResult(0, sourceService.getMessage("SUCCESS"));
        mr.setData(uri);
        return mr.toString();
    } catch (OSSException oe) {
        return MessageResult.error(500, oe.getErrorMessage()).toString();
    } catch (ClientException ce) {
        System.out.println("Error Message: " + ce.getMessage());
        return MessageResult.error(500, ce.getErrorMessage()).toString();
    } catch (Throwable e) {
        e.printStackTrace();
        return MessageResult.error(500, sourceService.getMessage("REQUEST_FAILED")).toString();
    } finally {
        ossClient.shutdown();
    }
}
 
Example 20
Source File: UploadController.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
/**
 * 上传base64处理后的图片
 *
 * @param base64Data
 * @return
 */
@RequestMapping(value = "/upload/oss/base64", method = RequestMethod.POST)
@ResponseBody
public MessageResult base64UpLoad(@RequestParam String base64Data) {
    MessageResult result = new MessageResult();
    try {
        log.debug("上传文件的数据:" + base64Data);
        String dataPrix = "";
        String data = "";
        if (base64Data == null || "".equals(base64Data)) {
            throw new Exception(sourceService.getMessage("NOT_FIND_FILE"));
        } else {
            String[] d = base64Data.split("base64,");
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                throw new Exception(sourceService.getMessage("DATA_ILLEGAL"));
            }
        }
        log.debug("对数据进行解析,获取文件名和流数据");
        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {//data:image/jpeg;base64,base64编码的jpeg图片数据
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {//data:image/x-icon;base64,base64编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {//data:image/gif;base64,base64编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {//data:image/png;base64,base64编码的png图片数据
            suffix = ".png";
        } else {
            throw new Exception(sourceService.getMessage("FORMAT_NOT_SUPPORT"));
        }
        String directory = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
        String key = directory + GeneratorUtil.getUUID() + suffix;

        //因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
        byte[] bs = Base64Utils.decodeFromString(data);
        OSSClient ossClient = new OSSClient(aliyunConfig.getOssEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
        try {
            //使用apache提供的工具类操作流
            InputStream is = new ByteArrayInputStream(bs);
            //FileUtils.writeByteArrayToFile(new File(Global.getConfig(UPLOAD_FILE_PAHT), tempFileName), bs);
            ossClient.putObject(aliyunConfig.getOssBucketName(), key, is);
            String uri = aliyunConfig.toUrl(key);
            MessageResult mr = new MessageResult(0, sourceService.getMessage("UPLOAD_SUCCESS"));
            mr.setData(uri);
            mr.setMessage(sourceService.getMessage("UPLOAD_SUCCESS"));
            log.debug("上传成功,key:{}", key);
            return mr;
        } catch (Exception ee) {
            log.info(ee.getMessage());
            throw new Exception(sourceService.getMessage("FAILED_TO_WRITE"));
        }
    } catch (Exception e) {
        log.debug("上传失败," + e.getMessage());
        result.setCode(500);
        result.setMessage(e.getMessage());
    }
    return result;
}