在android中高效上传图像到服务器

q3aa0525  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(193)

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

//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.");

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

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题