安卓post 提交图片流和字符数据

<?php
    $target_path  = "./upload/";//接收文件目录
    $target_path = $target_path . basename( $_FILES[‘uploadedfile‘][‘name‘]);
    if(move_uploaded_file($_FILES[‘uploadedfile‘][‘tmp_name‘], $target_path)) {
       echo "The file ".  basename( $_FILES[‘uploadedfile‘][‘name‘]). " has been uploaded";
    }  else{
       echo "There was an error uploading the file, please try again!" . $_FILES[‘uploadedfile‘][‘error‘];
    }
    ?>

android

package com.figo.uploadfile;
 
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
 
public class UploadfileActivity extends Activity
{
  // 要上传的文件路径,理论上可以传输任何文件,实际使用时根据需要处理
  private String uploadFile = "/sdcard/testimg.jpg";
  private String srcPath = "/sdcard/testimg.jpg";
  // 服务器上接收文件的处理页面,这里根据需要换成自己的
  private String actionUrl = "http://10.100.1.208/receive_file.php";
  private TextView mText1;
  private TextView mText2;
  private Button mButton;
 
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 
    mText1 = (TextView) findViewById(R.id.myText2);
    mText1.setText("文件路径:\n" + uploadFile);
    mText2 = (TextView) findViewById(R.id.myText3);
    mText2.setText("上传网址:\n" + actionUrl);
    /* 设置mButton的onClick事件处理 */
    mButton = (Button) findViewById(R.id.myButton);
    mButton.setOnClickListener(new View.OnClickListener()
    {
      @Override
      public void onClick(View v)
      {
        uploadFile(actionUrl);
      }
    });
  }
 
  /* 上传文件至Server,uploadUrl:接收文件的处理页面 */
  private void uploadFile(String uploadUrl)
  {
    String end = "\r\n";
    String twoHyphens = "--";
    String boundary = "******";
    try
    {
      URL url = new URL(uploadUrl);
      HttpURLConnection httpURLConnection = (HttpURLConnection) url
          .openConnection();
      // 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃
      // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
      httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K
      // 允许输入输出流
      httpURLConnection.setDoInput(true);
      httpURLConnection.setDoOutput(true);
      httpURLConnection.setUseCaches(false);
      // 使用POST方法
      httpURLConnection.setRequestMethod("POST");
      httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
      httpURLConnection.setRequestProperty("Charset", "UTF-8");
      httpURLConnection.setRequestProperty("Content-Type",
          "multipart/form-data;boundary=" + boundary);
 
      DataOutputStream dos = new DataOutputStream(
          httpURLConnection.getOutputStream());
      dos.writeBytes(twoHyphens + boundary + end);
      dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
          + srcPath.substring(srcPath.lastIndexOf("/") + 1)
          + "\""
          + end);
      dos.writeBytes(end);
 
      FileInputStream fis = new FileInputStream(srcPath);
      byte[] buffer = new byte[8192]; // 8k
      int count = 0;
      // 读取文件
      while ((count = fis.read(buffer)) != -1)
      {
        dos.write(buffer, 0, count);
      }
      fis.close();
 
      dos.writeBytes(end);
      dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
      dos.flush();
 
      InputStream is = httpURLConnection.getInputStream();
      InputStreamReader isr = new InputStreamReader(is, "utf-8");
      BufferedReader br = new BufferedReader(isr);
      String result = br.readLine();
 
      Toast.makeText(this, result, Toast.LENGTH_LONG).show();
      dos.close();
      is.close();
 
    } catch (Exception e)
    {
      e.printStackTrace();
      setTitle(e.getMessage());
    }
  }
}

参数比较全的

public static String post(String actionUrl, Map<String, String> params,
        Map<String, File> files) throws IOException {
      StringBuilder sb2 = new StringBuilder();
      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");
      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){
        //int i = 0;
        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"+(i++)+"\"; filename=\""+file.getKey()+"\""+LINEND);
          sb1.append("Content-Disposition: form-data; name=\"userupfile\"; filename=\""+file.getKey()+"\""+LINEND);
          sb1.append("Content-Type: application/octet-stream; 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(); 

      int res = conn.getResponseCode();
      InputStream in = null;
      if (res == 200) {
        in = conn.getInputStream();
        int ch; 

        while ((ch = in.read()) != -1) {
          sb2.append((char) ch);
        }
        Log.i("CAMERA", sb2.toString());
      }

      return in == null ? null : sb2.toString();
    }
时间: 2024-08-20 20:54:21

安卓post 提交图片流和字符数据的相关文章

JAVA基础学习day22--IO流四-对象序列化、管道流、RandomAccessFile、DataStream、ByteArrayStream、转换流的字符编码

一.对象序列化 1.1.对象序列化 被操作的对象需要实现Serializable接口 1.2.对象序列化流ObjectOutputStream与ObjectInputStream ObjectInputStream 对以前使用 ObjectOutputStream 写入的基本数据和对象进行反序列化. ObjectOutputStream 和 ObjectInputStream 分别与 FileOutputStream 和 FileInputStream 一起使用时,可以为应用程序提供对对象图形的

【JAVA IO流之字符流】

一.概述. java对数据的操作是通过流的方式.java用于操作流的对象都在IO包中.流按照操作数据不同分为两种,字节流和字符流.流按照流向分为输入流,输出流. 输入输出的“入”和“出”是相当于内存来说的. 字符流:字节流读取文字字节数据后,不直接操作,而是先查指定的编码表,获取对应的文字,再对这个文字进行操作.简单来说就是字节流+码表. 在IO流中,字节流的顶层父类是Writer和Reader. 二.java.io.FileWriter类. public class FileWriterext

Java:IO流之字符流Reader、Writer详解

java.io包中:字符流 字符流的两个抽象基类: Reader         Writer 文件的读取:Reader抽象类(java.io包中) 直接子类的构造方法: FileReader(File file) 在给定从中读取数据的 File 的情况下创建一个新 FileReader. FileReader(FileDescriptor fd) 在给定从中读取数据的 FileDescriptor 的情况下创建一个新 FileReader. FileReader(String fileName

JAVA之旅(二十四)——I/O流,字符流,FileWriter,IOException,文件续写,FileReader,小练习

JAVA之旅(二十四)--I/O流,字符流,FileWriter,IOException,文件续写,FileReader,小练习 JAVA之旅林林总总也是写了二十多篇了,我们今天终于是接触到了I/O了.如果你初学,不懂IO流,你可以从前往后慢慢看,但是你工作了一段时间你会发现,流的使用场景以及技术点是非常的强硬的,我们势必要掌握这个知识点,如果你觉得翻阅API比较鼓噪,看视频得不到精髓,看书看不到要点,你就跟随我的JAVA之旅,一起去探索吧! 一.I/O概述 I/O全名:Input Output

黑马程序员——Java基础--IO流(一)---字符流和字节流

------Java培训.Android培训.iOS培训..Net培训.期待与您交流! ------- 一.IO流的介绍及体系 IO流用来处理设备之间的数据传输.java对数据的操作是通过流的方式.java用于操作流的对象都在IO包中. 输入流和输出流相对于内存设备而言:将外设中的数据读取到内存中:输入.将内存中的数据写出到外设中:输出. 流按照操作数据分为两种:字节流和字符流. 字符流的由来:其实就是字节流读取文字字节数据后,不直接操作而是先查指定的编码表,获取对应的文字,再对这个文字进行操作

IO流之字符输入流,字符输出流

在我们日常开发中,我们经常会遇到要上传文件的操作,实现这个都是通过IO流去实现的,这次写的是普通字符输入流和普通输出流,由于效率有点低所以我们在日常开发中不会用到. 所以这次的代码可能只是帮助到接触到java  IO流的初学者,在后面的文章我们会更新高效流文件流 注意:字符流只能用来传输文本文件,所以我们要实现所有类型复制还是要用字节流,字符流的底层也是用到字节流 话不多说直接上代码 字符输入流 public static void main(String[] args) throws IOEx

Java之 IO流、字符流、字节流、缓冲流、对象流等各种流

File类:使用Java进行操作文件,通过一些方法进行操作.比如创建文件,删除文件,判断是否存在,文件大小,文件的目录等等,还有文件夹的一些操作. IO流:根据类别可以进行分类. 按照流向:输入流Input 输出流Output 按照字节个数:字节流和字符流 字节流: InputStream:抽象类,无法直接使用,通过其子类FileInputStream,从文件中获取字节. OutputStream:抽象类,无法直接使用,通过其子类FileOutputStream,向文件写入字节. 字符流: Re

java字节缓冲流和字符缓冲流

一.字节缓冲流 1.介绍 字节缓冲流根据流的方向,分为: 1.写入数据到流中,字节缓冲输出流 BufferedOutputStream 2.读取流中的数据,字节缓冲输入流 BufferedInputStream 它们的内部都包含了一个缓冲区,通过缓冲区读写,就可以提高了IO流的读写速度 2.字节缓冲输出流BufferedOutputStream 构造方法: public BufferedOutputStream(OutputStream out):创建一个新的缓冲输出流,以将数据写入指定的底层输

【Java】IO流--文件字符流--FileReader、FileWriter

FileReader 作用:用于读取字符流 构造方法: FileReader(File file) 创建一个新的 FileReader ,给出 File读取. FileReader(String fileName) 创建一个新的 FileReader ,给定要读取的文件的名称. 常用方法: 1)int read();2)int read(char[] cbuf)3)int read(char[] cbuf,int off,int len);4) int available();5)close()