android 向服务器传输文件和参数

本文介绍如何在Android应用中实现将文件和参数通过POST请求上传到服务器,包括Android端的实现细节和服务器端的处理逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android端代码:

import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class UploadServerUtil {
    /**
     *
     * @param actionUrl 服务器url
     * @param params    参数封装为map类
     * @param file      文件
     * @return
     * @throws IOException
     */
    public static String upLoadFilePost(String actionUrl, Map<String, String> params, File file) throws IOException {
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";
        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setReadTimeout(5 * 1000);
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false);
        conn.setRequestMethod("POST"); // Post方式
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
                + ";boundary=" + BOUNDARY);

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        StringBuilder sb1 = new StringBuilder();

        /*
        上传参数
         */
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb1.append(PREFIX).append(BOUNDARY).append(LINEND)
                        .append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND)
                        .append("Content-Type: text/plain; charset=" + CHARSET + LINEND)
                        .append("Content-Transfer-Encoding: 8bit" + LINEND)
                        .append(LINEND).append(entry.getValue()).append(LINEND);
            }
        }

        // 发送文件数据
        if (file != null) {
//            for (Map.Entry<String, File> file : files.entrySet()) {

            sb1.append(PREFIX);
            sb1.append(BOUNDARY);
            sb1.append(LINEND);
            sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""
                    + file.getName() + "\"" + LINEND);
            sb1.append("Content-Type: application/octet-stream; charset="
                    + CHARSET + LINEND);
            sb1.append(LINEND);

//            }
        }

        outStream.write(sb1.toString().getBytes());
        InputStream is = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }

        is.close();
        outStream.write(LINEND.getBytes());

        // 请求结束标志
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();

        // 得到响应码
        int res = conn.getResponseCode();
        Log.e("TAG", "response code:"+res);
        outStream.close();
        conn.disconnect();
        if(res==200) {
            String oneLine;
            StringBuffer response = new StringBuffer();
            BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((oneLine = input.readLine()) != null) {
                response.append(oneLine);
            }
            return response.toString();
        }else
        return "false";
    }

}

服务器代码:

 @PostMapping("what")
    public String what(MultipartFile file, String username){
        System.out.println(username);
        System.out.println(file.getSize());
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        //do something to file
        return "success";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值