Nodejs 安卓客户端上传文件怎么写?

Nodejs 安卓客户端上传文件怎么写?

安卓端上传文件(图片)到node,安卓端应该怎么写,什么杨的格式?

6 回复

Node.js 安卓客户端上传文件怎么写?

在安卓应用中上传文件到Node.js服务器通常涉及使用HTTP客户端来发送请求。在Android端,你可以使用HttpURLConnection或者第三方库如RetrofitVolley来实现文件上传功能。本文将通过一个简单的示例来展示如何使用HttpURLConnection来实现这一功能。

Android 端代码

首先,你需要创建一个方法来处理文件上传。这里我们假设你已经有一个选择文件的方法,并且文件路径存储在一个字符串变量中。

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUploader {

    public void uploadFile(String filePath) {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        FileInputStream fileInputStream = null;

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024; // 1MB

        try {
            File file = new File(filePath);
            fileInputStream = new FileInputStream(file);

            URL url = new URL("http://your-nodejs-server.com/upload");
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true); // 允许输入流
            connection.setDoOutput(true); // 允许输出流
            connection.setUseCaches(false); // 不使用缓存
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("file", filePath);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + filePath + "\"" + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            fileInputStream.close();
            outputStream.flush();
            outputStream.close();

            System.out.println("Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Node.js 端代码

接下来,我们需要在Node.js服务器端设置一个路由来接收上传的文件。这里我们将使用Express框架和Multer中间件来处理文件上传。

const express = require('express');
const multer = require('multer');
const path = require('path');

const app = express();
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/');
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + path.extname(file.originalname)); // 使用时间戳作为文件名
    }
});

const upload = multer({ storage: storage });

app.post('/upload', upload.single('file'), (req, res) => {
    if (!req.file) {
        return res.status(400).send('No file uploaded.');
    }
    res.send(`File uploaded successfully. Filename: ${req.file.filename}`);
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

总结

以上代码展示了如何在Android端使用HttpURLConnection上传文件到Node.js服务器,并在服务器端使用Express和Multer处理文件上传。确保你的Node.js服务器正在运行,并且可以访问你指定的URL。


安卓开发不熟悉,我只能提供个思路了,一种可以使用socket直接发送,还有一种就是构造post请求,就好像浏览器上传文件一样上传到编写好的服务器端。

用apache httpclient 或者 java 标准 net 包里面的类 就可以实现的,我以前做过,不过过了好久了,记不清了,你google 下 httpclient(android) 上传 图片(文件)应该可以收到类似案例。

上传文件都是用base64把文件编码成字符串,然后post字符串到服务器端,在服务端再解析

要在安卓客户端上传文件(例如图片)到Node.js服务器,你需要编写两个主要部分的代码:安卓客户端的代码用于选择和发送文件,以及Node.js服务器端的代码用于接收和处理文件。

安卓客户端

首先,在安卓客户端,你需要使用HttpURLConnection或第三方库如Retrofit来发送POST请求。下面是一个使用HttpURLConnection的例子:

  1. 选择文件: 使用Intent来启动文件选择器。

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivityForResult(intent, 1);
    
  2. 发送文件: 在onActivityResult中获取文件路径并发送:

    public void uploadFile(String filePath) {
        try {
            URL url = new URL("http://yourserver.com/upload");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    
            OutputStream os = conn.getOutputStream();
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(os), true);
    
            // 添加文件数据
            writer.append("--" + boundary).append("\r\n")
                .append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append("\r\n")
                .append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName())).append("\r\n")
                .append("Content-Transfer-Encoding: binary").append("\r\n")
                .append("\r\n").flush();
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush(); // Finish writing the file
            fis.close();
    
            writer.append("\r\n--" + boundary + "--\r\n").flush();
    
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 处理成功响应
            } else {
                // 处理错误
            }
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

Node.js 服务器端

在Node.js服务器端,你可以使用multer中间件来处理文件上传:

const express = require('express');
const multer = require('multer');

const app = express();

// 配置multer存储引擎
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/') // 存储位置
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
    }
});

const upload = multer({ storage: storage });

app.post('/upload', upload.single('file'), (req, res, next) => {
    console.log(req.file); // 文件信息
    console.log(req.body); // 其他表单数据
    res.send('File uploaded successfully!');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

确保你的Node.js服务器监听正确的端口,并且正确处理文件上传。这样你就可以从安卓客户端上传文件到Node.js服务器了。

回到顶部