import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
 
 
public class PostFile {
  public static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
 
    HttpPost httppost = newHttpPost("http://localhost/projects/java/upload.php");
    File file = new File("c:/1.jpg");
    File file2 = new File("c:/12.jpg");
    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    ContentBody cbFile2 = new FileBody(file2, "image/jpeg");
     
    StringBody username = new StringBody("username");
    mpEntity.addPart("userfile", cbFile);
    mpEntity.addPart("userfile2", cbFile2);
    mpEntity.addPart("username", username);
 
    httppost.setEntity(mpEntity);
     
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
 
    System.out.println(response.getStatusLine());
     
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }
 
    httpclient.getConnectionManager().shutdown();
  }
}

-------------------------------------------------------------------------

php:

 
code
 
<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
  echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
  move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']);
  move_uploaded_file ($_FILES['userfile2'] ['tmp_name'], $_FILES['userfile2'] ['name']);
 
 
else {
  echo "Possible file upload attack: ";
  echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
  print_r($_FILES);
}
 
$fp=fopen("t.txt","w");
fwrite ( $fp, $_POST['username'] );
fclose($fp);
?>
arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()