如何在android中将图像发布到服务器 [英] How to post an image to server in android
本文介绍了如何在android中将图像发布到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将图像上传到服务器?在API级别23中不推荐使用MultiPArtEntity和MultiPartEntityBuilder类。我们可以使用HTTPUrlConnection或者排球吗?
How do I upload an image to the Server? Both MultiPArtEntity and MultiPartEntityBuilder classes are deprecated in API level 23. Can we do this using HTTPUrlConnection or volley?
推荐答案
我建议你使用OkHttp。有关它的更多详细信息,请参阅以下内容:
I suggest that you use OkHttp. More details about it you can find at the following:
请参阅我从可绘制文件夹上传PNG文件的基本示例代码远程Web服务。希望这会有所帮助!
Please refer to my basic sample code that uploads a PNG file from drawable folder to remote web service. Hope this helps!
...
mTextView = (TextView) findViewById(R.id.textView);
mHandler = new Handler(Looper.getMainLooper());
...
Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
if (drawable != null) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
final byte[] bitmapdata = stream.toByteArray();
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"ic_launcher.png\""),
RequestBody.create(MEDIA_TYPE_PNG, bitmapdata))
.build();
final Request request = new Request.Builder()
.url("http://myserver/api/files")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Request request, final IOException e) {
Log.e(LOG_TAG, e.toString());
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
mTextView.setText(e.toString());
}
});
}
@Override
public void onResponse(Response response) throws IOException {
final String message = response.toString();
Log.i(LOG_TAG, message);
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
mTextView.setText(message);
}
});
}
});
}
这篇关于如何在android中将图像发布到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文