Android上传文件到服务器

本文介绍两种在Android应用中实现文件上传的方法。一种方法通过构造multipart/form-data格式的数据包,使用HttpURLConnection进行POST请求来上传文件及表单数据;另一种方法简化了上传过程,直接在请求体中构建文件数据并发送。

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


方法1:

public void uploadFile(){

String name=URLEncoder.encode(text1.getText().toString(),"utf-8");  
String pass=URLEncoder.encode(text2.getText().toString(),"utf-8"); 
         Map<String, String> params = new HashMap<String, String>();       
         params.put("NAME", name);   
         params.put("PASSWORD", pass);
         
        post("http://192.168.1.120/dev/index.php/Device/UploadFile?filename=111&filetype=IMAGE", params, upfiles);
}

Map<String, File> upfiles = new HashMap<String, File>();   

void getFile() {         
        File file = new File("/sdcard/");    
        File[] files = file.listFiles(new fileFilter());     
        
        for (File f: files) {       
        upfiles.put(f.getName(), new File("/sdcard/"+f.getName()));
               
        }          
         //  Toast.makeText(this, filename, Toast.LENGTH_LONG).show();   
            
        }     

class fileFilter implements FilenameFilter {    
        @Override          
        public boolean accept(File dir, String filename) {   
            return filename.endsWith(".mp3");    
         }     
     }  

// 上传代码,第一个参数,为要使用的URL,第二个参数,为表单内容,第三个参数为要上传的文件,可以上传多个文件,这根据需要页定  
    public static boolean post(String actionUrl,Map<String, String> params,Map<String, File> files) 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);  
        // 首先组拼文本类型的参数  
        StringBuilder sb = new StringBuilder();  
        for (Map.Entry<String, String> entry : params.entrySet()) {  
            sb.append(PREFIX);  
            sb.append(BOUNDARY);  
            sb.append(LINEND);  
            sb.append("Content-Disposition: form-data; name=\""  
                    + entry.getKey() + "\"" + LINEND);  
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);  
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);  
            sb.append(LINEND);  
            sb.append(entry.getValue());  
            sb.append(LINEND);  
        }  
        DataOutputStream outStream = new DataOutputStream(  
                conn.getOutputStream());  
        outStream.write(sb.toString().getBytes());  
        // 发送文件数据  
        if (files != null)  
            for (Map.Entry<String, File> file : files.entrySet()) {  
                StringBuilder sb1 = new StringBuilder();  
                sb1.append(PREFIX);  
                sb1.append(BOUNDARY);  
                sb1.append(LINEND);  
                sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""  
                        + file.getKey() + "\"" + LINEND);  
                sb1.append("Content-Type: multipart/form-data; charset="  
                        + CHARSET + LINEND);  
                sb1.append(LINEND);  
                outStream.write(sb1.toString().getBytes());  
                InputStream is = new FileInputStream(file.getValue());  
                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();  
        // 得到响应码  
        boolean success = conn.getResponseCode()==200;  
        InputStream in = conn.getInputStream();  
        InputStreamReader isReader = new InputStreamReader(in);  
        BufferedReader bufReader = new BufferedReader(isReader);  
        String line = null;  
        String data = "getResult=";  
        while ((line = bufReader.readLine()) != null)  
            data += line;  
        
        outStream.close();  
        conn.disconnect();  
        return success;  

    }  


方法2:

final String ENCORDING="UTF-8";
public boolean upload(String filepath) throws Exception {
String boundary = "---------------------------7db1c523809b2";//+java.util.UUID.randomUUID().toString();//
// 分割线
File file = new File(filepath);

String fileName=new String("哈哈嗨".getBytes(),"ISO-8859-1");
// 用来解析主机名和端口
URL url = new URL("http://192.168.1.120/dev/index.php/Device/UploadFile?filename="+fileName+"&filetype=IMAGE");
// 用来开启连接 
StringBuilder sb = new StringBuilder();
// 用来拼装请求


/*// username字段
    sb.append("--" + boundary + "\r\n");
    sb.append("Content-Disposition: form-data; name=\"username\"" + "\r\n");
    sb.append("\r\n");
    sb.append(username + "\r\n");


    // password字段
    sb.append("--" + boundary + "\r\n");
    sb.append("Content-Disposition: form-data; name=\"password\"" + "\r\n");
    sb.append("\r\n");
    sb.append(password + "\r\n");*/
   
// 文件部分
sb.append("--" + boundary + "\r\n");
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + filepath + "\"" + "\r\n");
sb.append("Content-Type: application/octet-stream" + "\r\n");
sb.append("\r\n");


// 将开头和结尾部分转为字节数组,因为设置Content-Type时长度是字节长度
byte[] before = sb.toString().getBytes(ENCORDING);
byte[] after = ("\r\n--" + boundary + "--\r\n").getBytes(ENCORDING);


// 打开连接, 设置请求头
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
conn.setRequestProperty("Content-Length", before.length + file.length() + after.length + "");

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


// 获取输入输出流
OutputStream out = conn.getOutputStream();
FileInputStream fis = new FileInputStream(file);
// 将开头部分写出
out.write(before);


// 写出文件数据
byte[] buf = new byte[1024*5];
int len;
while ((len = fis.read(buf)) != -1)
out.write(buf, 0, len);


// 将结尾部分写出
out.write(after);

InputStream in = conn.getInputStream();  
InputStreamReader isReader = new InputStreamReader(in);  
BufferedReader bufReader = new BufferedReader(isReader);  
       String line = null;  
       String data = "getResult=";  
       while ((line = bufReader.readLine()) != null)  
           data += line;     
       Log.e("fromServer", "result="+data);
       boolean sucess=conn.getResponseCode() == 200;
       in.close();
fis.close();
out.close();
conn.disconnect();

return sucess;  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值