android上传图片文件至c 服务器,Android :okhttp+Springmvc文件解析器实现android向服务器上传照片...

A.前言:为了解决安卓端向服务器上传照片的问题

1.获得相册权限,选取照片,取到照片的url

2.使用okhttp访问服务器并向服务器传照片

3.配置springmvc文件解析器

4.搭建服务器,获取数据保存照片

B.Android添加一个按钮和一个ImageView,设置它的点击事件,打开相册选择照片,解析得到照片的本机url,并把照片显示到ImageView里

添加权限:

导包:

compile 'com.squareup.okhttp3:okhttp:3.4.1'

按钮事件:打开相册选取照片    调用startActivityForResult();

protected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button button=(Button)findViewById(R.id.button );w

image=(ImageView) findViewById(R.id.image);

button.setOnClickListener(newView.OnClickListener() {

@Overridepublic voidonClick(View view) {

Intent intent= newIntent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");

startActivityForResult(intent,100);

}

});

}

重写onActivityResult()方法  解析照片获得url 覆给全局变量,并把照片显示到imageView。调用自定义的uploadImage(),向服务器发送数据

@Overridepublic void onActivityResult(int requestCode, intresultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);switch(requestCode) {case 100:switch(resultCode) {caseRESULT_OK:

Uri uri=data.getData();

img_src= uri.getPath();//这是本机的图片路径

ContentResolver cr = this.getContentResolver();try{

Bitmap bitmap=BitmapFactory.decodeStream(cr.openInputStream(uri));/*将Bitmap设定到ImageView*/image.setImageBitmap(bitmap);

String[] proj={MediaStore.Images.Media.DATA};

CursorLoader loader= new CursorLoader(this, uri, proj, null, null, null);

Cursor cursor=loader.loadInBackground();if (cursor != null) {int column_index =cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

cursor.moveToFirst();

img_src= cursor.getString(column_index);//图片实际路径

}

cursor.close();this.uploadImage();

}catch(FileNotFoundException e) {

Log.e("cwd", e.getMessage(), e);

}break;

}break;

}

}

实现uploadImage(),使用okhttp向服务器传数据

public voiduploadImage() {

Log.d("cwd","uploadImage");new Thread(newRunnable() {

@Overridepublic voidrun() {

File file=newFile(img_src);

RequestBody requestBody= newMultipartBody.Builder()

.setType(MultipartBody.FORM)

.addFormDataPart("jsonfile", file.getName(),

RequestBody.create(MediaType.parse("multipart/form-data"), file))//文件

.build();

Request request= newRequest.Builder()

.url("http://3i157k1732.qicp.vip/springmvc03/jsonsrc").post(requestBody)

.build();

OkHttpClient client=newOkHttpClient();

client.newCall(request).enqueue(newCallback() {

@Overridepublic voidonFailure(Call call, IOException e) {

Log.d("cwd", "上传失败"+e.getLocalizedMessage());

}

@Overridepublic void onResponse(Call call, Response response) throwsIOException {

Log.d("cwd","上传成功"+response.body().string());

}

});

}

}).start();

}

C.服务器端,配置springmvc文件解析器,定义照片数据处理的方法

idea导包:

com.fasterxml.jackson.core

jackson-annotations

2.10.0

在Springmvc的配置文件中配置文件解析器:注意   bean 的id必须为multipartResolver

定义处理方法:  必须使用RequestParam来绑定参数,值为okhttp上传数据的key值

注意!!!

0f0547c511f1cdf7cf28f6d82ff0903d.png

@RequestMapping(value = "/jsonsrc")public String jsonsrc(HttpServletRequest request,@RequestParam("jsonfile") MultipartFile jsonfile) throwsIOException {

System.out.println("jsonsrc");

String path=request.getSession().getServletContext().getRealPath("/uploads/");

File file=newFile(path);if(!file.exists()){

file.mkdir();

}

String filename=jsonfile.getOriginalFilename();

String uuid= UUID.randomUUID().toString().replace("-","");

filename=uuid+filename;

jsonfile.transferTo(newFile(path,filename));return "succes";

}

这样就完成了!!!

okhttp用来访问网络,可以拿数据,也可以向服务器传数据!

使用springmvc文件解析器,让我们不用去注重解析文件,只需要保存文件!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值