调用OSS接口上传图片:
public void uploadImage(final String path, final String name, final Activity activity) { //上传照片的函数 new Thread(new Runnable() { @Override public void run() { OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(ACCESS_ID, ACCESS_KEY); ClientConfiguration conf = new ClientConfiguration(); conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒 conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒 conf.setMaxConcurrentRequest(8); // 最大并发请求数,默认5个 conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次 // oss为全局变量,OSS_ENDPOINT是一个OSS区域地址 oss = new OSSClient(activity.getApplicationContext(), OSS_ENDPOINT, credentialProvider, conf); // 构造上传请求。 PutObjectRequest put = new PutObjectRequest("sean1246", name, path); put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() { @Override public void onProgress(PutObjectRequest request, long currentSize, long totalSize) { Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize); } }); // 文件元信息的设置是可选的。 // ObjectMetadata metadata = new ObjectMetadata(); // metadata.setContentType("application/octet-stream"); // 设置content-type。 // metadata.setContentMD5(BinaryUtil.calculateBase64Md5(uploadFilePath)); // 校验MD5。 // put.setMetadata(metadata); try { // meta设置请求头,解决访问图片地址直接下载 ObjectMetadata meta = new ObjectMetadata(); meta.setContentType(getContentType(path.substring(path.lastIndexOf(".")))); put.setMetadata(meta); PutObjectResult putResult = oss.putObject(put); Log.d("PutObject", "UploadSuccess"); Log.d("ETag", putResult.getETag()); Log.d("RequestId", putResult.getRequestId()); } catch (ClientException e) { // 本地异常,如网络异常等。 e.printStackTrace(); } catch (ServiceException e) { // 服务异常。 Log.e("RequestId", e.getRequestId()); Log.e("ErrorCode", e.getErrorCode()); Log.e("HostId", e.getHostId()); Log.e("RawMessage", e.getRawMessage()); } } }).start(); }
public static String getContentType(String FilenameExtension) { //设置contenttype if (FilenameExtension.equalsIgnoreCase(".bmp")) { return "image/bmp"; } if (FilenameExtension.equalsIgnoreCase(".gif")) { return "image/gif"; } if (FilenameExtension.equalsIgnoreCase(".jpeg") || FilenameExtension.equalsIgnoreCase(".jpg") || FilenameExtension.equalsIgnoreCase(".png")) { return "image/jpg"; } if (FilenameExtension.equalsIgnoreCase(".html")) { return "text/html"; } if (FilenameExtension.equalsIgnoreCase(".txt")) { return "text/plain"; } if (FilenameExtension.equalsIgnoreCase(".vsd")) { return "application/vnd.visio"; } if (FilenameExtension.equalsIgnoreCase(".pptx") || FilenameExtension.equalsIgnoreCase(".ppt")) { return "application/vnd.ms-powerpoint"; } if (FilenameExtension.equalsIgnoreCase(".docx") || FilenameExtension.equalsIgnoreCase(".doc")) { return "application/msword"; } if (FilenameExtension.equalsIgnoreCase(".xml")) { return "text/xml"; } return "image/jpg"; }