首页 > 解决方案 > 在Android中有效地将图像上传到服务器

问题描述

我有一个需要将图像发送到服务器的应用程序。现在我正在这样做:

//We have a variable "image" that is the Bitmap that we want to send
File imagesFolder = new File(getCacheDir(), "images");
File file = null;
try {
    if(imagesFolder.exists() || imagesFolder.mkdirs()) {
        file = new File(imagesFolder, "input.jpg");
        FileOutputStream stream = new FileOutputStream(file);
        //checkWifiOnAndConnected returns true if wifi is on and false if mobile data is being used
        image.compress(Bitmap.CompressFormat.JPEG, checkWifiOnAndConnected() ? 90 : 80, stream);
        stream.flush();
        stream.close();
    }
} catch (IOException e) {
    Log.d("Error", "IOException while trying to write file for sharing: " + e.getMessage());
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", new FileBody(file));
HttpEntity entity = builder.build();
URL url = new URL(serverUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(40000);
conn.setConnectTimeout(40000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(entity.getContentLength());
conn.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
entity.writeTo(os);
os.close();
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK)
    Log.e("UPLOAD", "HTTP 200 OK.");

它可以工作,但有点慢,特别是在使用移动数据时(显然)。我想知道是否有更有效和更快的方式来发送这张图片。

标签: javaandroidpostbitmaphttpurlconnection

解决方案


推荐阅读