weex☞oss上传图片(android篇)
2018-12-14 本文已影响27人
小学生的博客
oss上传,其实使用的原生Android的oss-android-sdk,算不上weex上传,本来想实现前端上传,weex的input不能设置type=“file”(但是可以使用原生打开相册返回地址的),后来直接使用了upload.js进行上传,但是看样子都是操作dom什么的,官方STS模式文档看的也晕晕乎乎的,算来还是用原生的吧。
话不多说,直接开始
- 1.android/app/ build.gradle下新增
compile 'com.zhy:okhttputils:2.6.2' // 有自己的网络封装就不需要这个了
compile 'com.aliyun.dpa:oss-android-sdk:+'
- 2.新增 UploadImageModule
public class UploadImageModule extends WXModule {
public final static int GALLERY_REQUEST_CODE = 1;
public String AccessKeyId, AccessKeySecret, SecurityToken;
protected JSCallback callback;
// 从前端传来的参数(可以携带其他参数,比如携带token,
// 避免接口无法拦截访问问题),这里是获取临时密钥的接口地址
String baseUrl;
@JSMethod(uiThread = true)
public void choosePhoto(Object options, JSCallback callback) {
if (ContextCompat.checkSelfPermission(mWXSDKInstance.getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((WXPageActivity) mWXSDKInstance.getContext(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
GALLERY_REQUEST_CODE);
} else {
choosePhoto();
}
this.callback = callback;
JSONObject obj = null;
try {
obj = new JSONObject(options.toString());
baseUrl = obj.optString("baseUrl");
} catch (JSONException e) {
e.printStackTrace();
}
getOssKey();
}
// 通过后端接口直接获取 临时的AccessKeyId AccessKeySecret SecurityToken
// 假如不需要获取,那就不需要该方法,直接在下面初始化 OSSStsTokenCredentialProvider时候,
// 填写自己的keyid、secret、 token
public void getOssKey() {
String url = baseUrl + "获取临时密钥的接口";
OkHttpUtils
.get()
.url(url)
.id(100)
.build()
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
}
@Override
public void onResponse(String response, int id) {
try {
JSONObject obj = new JSONObject(response);
JSONObject data = obj.getJSONObject("data");
AccessKeyId = data.optString("AccessKeyId");
AccessKeySecret = data.optString("AccessKeySecret");
SecurityToken = data.optString("SecurityToken");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
private void choosePhoto() {
Intent intentToPickPic = new Intent(Intent.ACTION_PICK, null);
intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
((Activity) (mWXSDKInstance.getContext())).startActivityForResult(intentToPickPic, GALLERY_REQUEST_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == WXPageActivity.RESULT_OK) {
switch (requestCode) {
case GALLERY_REQUEST_CODE: {
try {
Uri selectedImage = data.getData();
String[] filePathColumns = {MediaStore.Images.Media.DATA};
Cursor c = mWXSDKInstance.getContext().getContentResolver().query(selectedImage, filePathColumns, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePathColumns[0]);
final String picturePath = c.getString(columnIndex);
c.close();
new Thread(new Runnable() {
@Override
public void run() {
handlerUpLoad(picturePath);
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
// 这个方法才是上传的关键
public void handlerUpLoad(String path) {
// 自己的endpoint
String endpoint = "http://oss-cn-beijing.aliyuncs.com";
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(AccessKeyId, AccessKeySecret, SecurityToken);
ClientConfiguration conf = new ClientConfiguration();
conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个
conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次
OSS oss = new OSSClient(mWXSDKInstance.getContext(), endpoint, credentialProvider, conf);
String objectname = path.substring(path.lastIndexOf("/") + 1, path.length());
final String upLoadName = " userImage/" + objectname;
// upLoadName是上传到oss上面的文件名,这里是userImage/test.jpg,
// 会自动在自己的“bucketName”存储空间下,创建一个 userImage的文件夹,
// 并在下面添加上传的文件test.jpg
// path是文件在本地的路径
Log.d("TAG-path", path);
Log.d("TAG-path", upLoadName);
//填上自己的bucketName
PutObjectRequest put = new PutObjectRequest("bucketName", upLoadName, path);
OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result) {
Log.d("status", result + "");
if (result.getStatusCode() == 200) {
Map data2 = new HashMap();
data2.put("result", true);
data2.put("upLoadName", upLoadName);
data2.put("message", "上传成功");
callback.invoke(data2);
} else {
callback.invoke("上传失败");
}
}
@Override
public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
if (clientExcepion != null) {
// 本地异常如网络异常等
clientExcepion.printStackTrace();
}
if (serviceException != null) {
// 服务异常
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
}
}
- 3.WXApplication
WXSDKEngine.registerModule("uploadImage", UploadImageModule.class);
- 4.前端使用
const uploadImage = weex.requireModule('uploadImage')
...
uploadPic() {
let options = {
baseUrl: ""
}
uploadImage.choosePhoto(options, (res) => {
modal.toast({
'message': res,
'duration': 1
})
})
}
这是最简单的上传方式,可以自行优化。