灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:2805回复:0

图片文件上传

楼主#
更多 发布于:2012-09-06 13:52


[java]        //一些定义的变量  
       private String newName = "image.jpg";
private String uploadFile = "/sdcard/apple.jpg";
//private String actionUrl = "http://localhost:8080/testCutPic/upload.php";  
//上传图片地址,上传的图片文件参数名为fileToUpload  
private String actionUrl="http://192.168.1.64/svn_ys/sousoutu/api/api_imgupload.php";
        //一些定义的变量
        private String newName = "image.jpg";
private String uploadFile = "/sdcard/apple.jpg";
//private String actionUrl = "http://localhost:8080/testCutPic/upload.php";
//上传图片地址,上传的图片文件参数名为fileToUpload
private String actionUrl="http://192.168.1.64/svn_ys/sousoutu/api/api_imgupload.php";
HttpClient请求客户端方式:

[html]               private void postFile(){
    
   HttpClient httpclient = new DefaultHttpClient();
   httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://192.168.1.64/svn_ys/sousoutu/api/api_imgupload.php");
    
    File file = new File(uploadFile);
//  File file2=new File(uploadFile);
    
    ContentBody cbFile = new FileBody(file, "image/jpeg");
//  ContentBody cbFile2 = new FileBody(file2, "image/jpeg");
    MultipartEntity mpEntity = new MultipartEntity();
  
    mpEntity.addPart("fileToUpload", cbFile);
//  mpEntity.addPart("fileToUpload2", cbFile2);
       //  mpEntity.addPart("字符串参数", new StringBody("user"));


    httppost.setEntity(mpEntity);
    
    Log.d("log", "请求信息: " + httppost.getRequestLine());
//   System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    HttpEntity resEntity = response.getEntity();
    
    Log.d("log", "响应信息:"+response.getStatusLine().toString());
   // System.out.println(response.getStatusLine());
    if (resEntity != null) {
      try {
          final String response_str=EntityUtils.toString(resEntity);
          Log.d("log", response_str);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
    if (resEntity != null) {
      try {
        resEntity.consumeContent();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

    httpclient.getConnectionManager().shutdown();
   }
                private void postFile(){
    
     HttpClient httpclient = new DefaultHttpClient();
     httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
      HttpPost httppost = new HttpPost("http://192.168.1.64/svn_ys/sousoutu/api/api_imgupload.php");
    
      File file = new File(uploadFile);
  //  File file2=new File(uploadFile);
    
      ContentBody cbFile = new FileBody(file, "image/jpeg");
  //  ContentBody cbFile2 = new FileBody(file2, "image/jpeg");
      MultipartEntity mpEntity = new MultipartEntity();
  
      mpEntity.addPart("fileToUpload", cbFile);
  //  mpEntity.addPart("fileToUpload2", cbFile2);
         //  mpEntity.addPart("字符串参数", new StringBody("user"));
  
      httppost.setEntity(mpEntity);
    
      Log.d("log", "请求信息: " + httppost.getRequestLine());
   //   System.out.println("executing request " + httppost.getRequestLine());
      HttpResponse response = null;
   try {
    response = httpclient.execute(httppost);
   } catch (ClientProtocolException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }
      HttpEntity resEntity = response.getEntity();
    
      Log.d("log", "响应信息:"+response.getStatusLine().toString());
     // System.out.println(response.getStatusLine());
      if (resEntity != null) {
        try {
         final String response_str=EntityUtils.toString(resEntity);
         Log.d("log", response_str);
   } catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
      }
      if (resEntity != null) {
        try {
    resEntity.consumeContent();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
      }
      httpclient.getConnectionManager().shutdown();
     }字节流的方式上传:

[html] private void uploadFile() {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
    URL url = new URL(actionUrl);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);

    con.setRequestMethod("POST");

    con.setRequestProperty("Connection", "Keep-Alive");
    con.setRequestProperty("Charset", "UTF-8");
    con.setRequestProperty("Content-Type",
            "multipart/form-data;boundary=" + boundary);

    DataOutputStream ds = new DataOutputStream(con.getOutputStream());
    ds.writeBytes(twoHyphens + boundary + end);
    ds.writeBytes("Content-Disposition: form-data; "
            + "name=\"file1\";filename=\"" + newName + "\"" + end);
    ds.writeBytes(end);

    FileInputStream fStream = new FileInputStream(uploadFile);

    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];

    int length = -1;

    while ((length = fStream.read(buffer)) != -1) {

        ds.write(buffer, 0, length);
    }
    ds.writeBytes(end);
    ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

    fStream.close();
    ds.flush();

    InputStream is = con.getInputStream();
    int ch;
    StringBuffer b = new StringBuffer();
    while ((ch = is.read()) != -1) {
        b.append((char) ch);
    }

    showDialog("上传成功" + b.toString().trim());

    ds.close();
} catch (Exception e) {
    e.printStackTrace();
    showDialog("上传失败" + e);
}
   private void uploadFile() {
  String end = "\r\n";
  String twoHyphens = "--";
  String boundary = "*****";
  try {
   URL url = new URL(actionUrl);
   HttpURLConnection con = (HttpURLConnection) url.openConnection();
   con.setDoInput(true);
   con.setDoOutput(true);
   con.setUseCaches(false);
   con.setRequestMethod("POST");
   con.setRequestProperty("Connection", "Keep-Alive");
   con.setRequestProperty("Charset", "UTF-8");
   con.setRequestProperty("Content-Type",
     "multipart/form-data;boundary=" + boundary);
   DataOutputStream ds = new DataOutputStream(con.getOutputStream());
   ds.writeBytes(twoHyphens + boundary + end);
   ds.writeBytes("Content-Disposition: form-data; "
     + "name=\"file1\";filename=\"" + newName + "\"" + end);
   ds.writeBytes(end);
   FileInputStream fStream = new FileInputStream(uploadFile);
   int bufferSize = 1024;
   byte[] buffer = new byte[bufferSize];
   int length = -1;
   while ((length = fStream.read(buffer)) != -1) {
    ds.write(buffer, 0, length);
   }
   ds.writeBytes(end);
   ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
   fStream.close();
   ds.flush();
   InputStream is = con.getInputStream();
   int ch;
   StringBuffer b = new StringBuffer();
   while ((ch = is.read()) != -1) {
    b.append((char) ch);
   }
   showDialog("上传成功" + b.toString().trim());
   ds.close();
  } catch (Exception e) {
   e.printStackTrace();
   showDialog("上传失败" + e);
  }
}

用到的dialog对话框,用来显示测试结果:

[html]    private void showDialog(String mess) {
w AlertDialog.Builder(TestuploadImageActivity.this)
.setTitle("Message").setMessage(mess)
.setNegativeButton("确定", new Dialoginterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
    }
}).show();




喜欢0 评分0
游客

返回顶部