如何在android中将图像发布到服务器

时间:2015-11-26 07:35:05

标签: http-post android-volley httpurlconnection image-uploading multipart

如何将图像上传到服务器?在API级别23中不推荐使用MultiPArtEntity和MultiPartEntityBuilder类。我们可以使用HTTPUrlConnection或者齐射吗?

2 个答案:

答案 0 :(得分:1)

你好以上答案是正确的并且已被接受但是这是将图像发布到服务器的最简单方法: -

在Android项目中使用来自andoid spring框架的rest api,只需创建新的自定义界面,如下所示: -

@Rest(rootUrl ="BASE_URL", converters = {ByteArrayHttpMessageConverter.class,
    FormHttpMessageConverter.class, StringHttpMessageConverter.class})
public interface CustomRest extends RestClientErrorHandling {

@Post("YourPostfixforUrl")
String _postImage(MultiValueMap<String, Object> multiValueMap);

}

使用以下代码创建您自己的RestErrorHandler: -

@EBean
public class CustomRestErrorHandler implements RestErrorHandler
{
    @Override
    public void onRestClientExceptionThrown(NestedRuntimeException e)
    {
        Log.e("NestedRuntimeException ", "NestedRuntimeException :- " + e.toString());
    }
}

在您的活动中,请致电以下代码: -

 @AfterInject
public void afterInject() {
    MultiValueMap<String, Object> ObjectMultiValueMap = new LinkedMultiValueMap<>();
    ObjectMultiValueMap.add("yourImageKey", new FileSystemResource(new File("yourFilePath")));
    doInBackground(myrest, ObjectMultiValueMap);
}

@Background
public void doInBackground(Myrest myrest, MultiValueMap<String, Object> multiValueMap) {
    myrest.setRestErrorHandler(myErrorHandler);

}

您的Gradle如下所示: -

def AAVersion = '3.3.2'    
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
apt "org.androidannotations:androidannotations:$AAVersion"
compile "org.androidannotations:androidannotations-api:$AAVersion"
compile 'org.springframework.android:spring-android-core:1.0.1.RELEASE'
compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'}

注意: - 您的活动必须是@Eactivity

- &GT;我猜androidannotation + rest是最好的节省时间并真诚地优化代码片段! 感谢

答案 1 :(得分:0)

我建议您使用OkHttp。有关它的更多详细信息,请参阅以下内容:

  

OkHttp - An HTTP & SPDY client for Android and Java applications

请参阅我的基本示例代码,该代码将PNG文件从drawable文件夹上传到远程Web服务。希望这有帮助!

...
    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);
                    }
                });
            }
        });
    }