【问题标题】:How to send an image from Android client to Node.js server via HttpUrlConnection?如何通过 HttpUrlConnection 将图像从 Android 客户端发送到 Node.js 服务器?
【发布时间】:2015-07-07 09:22:53
【问题描述】:

我正在尝试使用 HttpUrlConnection 将图像发送到服务器,因为它是 Google 推荐的。我决定将图像转换为 Base64 字符串并将其发送到我将其解码为 .jpg 文件的服务器。但是这种方法只适用于小尺寸的缩略图,我无法发送全尺寸的图像。

这里是安卓客户端代码:

 public static void postData(Bitmap imageToSend) {



        try

        {
            URL url = new URL("http://");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");

            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");

            conn.setReadTimeout(35000);
            conn.setConnectTimeout(35000);


            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            // writes a compress version of Bitmap to a specified outputstream
            imageToSend.compress(Bitmap.CompressFormat.JPEG, 100, bos);

            byte[] byteArray = bos.toByteArray();
            String imageEncoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("image", imageEncoded));


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));

            // getQuery is function for creating a URL encoded string
            writer.write(getQuery(params));

            System.out.println("Response Code: " + conn.getResponseCode());

            InputStream in = new BufferedInputStream(conn.getInputStream());
            Log.d("sdfs", "sfsd");
            BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = responseStreamReader.readLine()) != null)
                stringBuilder.append(line).append("\n");
            responseStreamReader.close();

            String response = stringBuilder.toString();
            System.out.println(response);

            bos.flush();
            bos.close();
            in.close();
            conn.disconnect();

        }

        catch(MalformedURLException e) {
            e.printStackTrace();
        }

        catch(IOException e) {
            e.printStackTrace();
        }


}

Node.js 服务器代码:

function base64_decode(base64str,file) {
   var bitmap = new Buffer(base64str,'base64');
   //writing into an image file
   fs.writeFile(file, bitmap);
   //write a text file
    console.log('File created from base64 encoded string');
}

app.post("/", function (req,res,next) {
        //requesting the value of the image key which is urlencoded base 64 string
        var image = req.body.image;
        console.log(req.body.image);
        base64_decode(image,'newImage.jpg');

        res.writeHead(200, {'Content-Type':'text/plain'});
        res.write('the image is saved');
        res.end();
        if (req.url != "/")
           next();
 

由于 BufferedWriter 的大小限制,我不能对全尺寸图像使用相同的方法 - base64 编码的字符串对于它来说太长了。

另一种方法是使用 HttpPost 和 MultipartEntity,但两者在 API22 中都已弃用,我不知道如何在服务器端处理请求。在其他示例中,使用了一些包装器,例如两个连字符、边界、crlf,但我找不到原因。

我需要一个 HttpUrlConnection 的例子

感谢任何帮助,因为我是 Android 和 node.js 的新手

【问题讨论】:

  • 如果你想避免与HttpURLConnection 混在一起,你可以看看DavidWebb。如果您使用 Express,则有一个带有 some sample code 的 test-api-server 显示如何完成上传。一般来说,我不建议使用 Base64,您可以在所有情况下上传二进制文件。你愿意接受这个图书馆和 Express 吗?
  • 我还是使用 Express。感谢您提供这些库,如果我无法弄清楚 HttpUrlConnection 问题,我会考虑使用它。但是,我在文档中看到它不支持分段上传

标签: javascript android node.js httpurlconnection android-bitmap


【解决方案1】:

我建议上传二进制数据。您可以将图像元数据(如名称、类型、用户 ID、...)作为 url 参数或自定义 http-headers (X-...)。

Android 客户端代码(未经测试!):

 public static void postData(Bitmap imageToSend) {
        try
        {
            URL url = new URL("http://myserver/myapp/upload-image");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");

            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");

            conn.setReadTimeout(35000);
            conn.setConnectTimeout(35000);

            // directly let .compress write binary image data
            // to the output-stream
            OutputStream os = conn.getOutputStream();
            imageToSend.compress(Bitmap.CompressFormat.JPEG, 100, os);
            os.flush();
            os.close();

            System.out.println("Response Code: " + conn.getResponseCode());

            InputStream in = new BufferedInputStream(conn.getInputStream());
            Log.d("sdfs", "sfsd");
            BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = responseStreamReader.readLine()) != null)
                stringBuilder.append(line).append("\n");
            responseStreamReader.close();

            String response = stringBuilder.toString();
            System.out.println(response);

            conn.disconnect();
        }
        catch(MalformedURLException e) {
            e.printStackTrace();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
}

Node.js,快递代码:

function rawBody(req, res, next) {
    var chunks = [];

    req.on('data', function(chunk) {
        chunks.push(chunk);
    });

    req.on('end', function() {
        var buffer = Buffer.concat(chunks);

        req.bodyLength = buffer.length;
        req.rawBody = buffer;
        next();
    });

    req.on('error', function (err) {
        console.log(err);
        res.status(500);
    });
}

app.post('/upload-image', rawBody, function (req, res) {

    if (req.rawBody && req.bodyLength > 0) {

        // TODO save image (req.rawBody) somewhere

        // send some content as JSON
        res.send(200, {status: 'OK'});
    } else {
        res.send(500);
    }

});

我将尝试解释 node.js 部分: 函数rawBody 充当 Express 中间件。当发出POST 请求时,将使用请求对象调用此函数。它为data、end 和error 事件注册侦听器。 data 事件将所有传入的数据块附加到缓冲区。当end 触发时,属性rawBody 在请求对象中创建并包含二进制数据(您的图像块)。 rawBody() 然后将控制权转移到下一个处理程序,该处理程序现在可以将 blob 保存到您的数据库或文件系统。

在处理非常大的数据块时,这种处理方式并不是最好的方法。最好将数据流式传输到文件或数据库中以节省内存。

【讨论】:

  • 就是这样!非常感谢!!!你为我节省了很多时间和精力!我没有完全理解 node.js 部分,我会研究它,或者如果你能简单地解释一下,我将非常感激!
【解决方案2】:

我还没有足够的分数,所以我必须写一个完整的答案而不是评论。

我想在 hgoebl 的答案中添加一些内容,这很棒,为我节省了很多时间!谢谢!

在刷新流之前,您必须添加这些行,因为没有它们我无法让它工作。

urlConnection.setRequestProperty("Content-Type", "multipart/form-data");
urlConnection.setFixedLengthStreamingMode(1024);

如果您想直接从您的 USB/SD 存储设备中读取数据,则无需解码您的位图并将其编码为压缩格式。喜欢就好

// ... set request header 

FileInputStream fis = new FileInputStream(filePath);

OutputStream os = new BufferedOutputStream(urlConnection.getOutputStream());
OutputStreamWriter out = new OutputStreamWriter(os);

byte[] buffer = new byte[1024];
int read;
while ((read = fis.read(buffer)) != -1) {
    os.write(buffer, 0, read);
}

... // flush and close

有了这个,您应该能够上传任何类型的二进制数据。

【讨论】:

  • 你好!您是如何定义内容类型的边界的?是 "\n" 吗?谢谢你的回答
猜你喜欢
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
  • 1970-01-01
  • 2016-12-12
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
相关资源
最近更新 更多