>  기사  >  백엔드 개발  >  안드로이드는 PHP 서버에 사진을 업로드

안드로이드는 PHP 서버에 사진을 업로드

WBOY
WBOY원래의
2016-08-08 09:22:361198검색

Android 코드

public class EX08_11 extends Activity
{
/* 변수 선언
* newName: 업로드 후 서버에 있는 파일 이름
* uploadFile: to 업로드할 파일 경로
* actionUrl: 서버에 해당하는 프로그램 경로*/
// private String newName="345444.jpg";
private String uploadFile="/sdcard/345444.jpg";
private String acti//***********/upload.php";
private TextView mText1;
private TextView mText2;
private Button mButton;

@Override
public void onCreate(Bundle selectedInstanceState)
{
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("Upload URL: n "+actionUrl);
/* mButton의 onClick 이벤트 처리 설정*/
mButton = (Button) findViewById(R.id.myButton);
mButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
uploadFile();
}
});
}

/* 파일 업로드 위치 서버 메소드 */
private void uploadFile()
{
// String end = "rn";
// String twoHyphens = "--";
String 경계 = "** ***";
try
{
URL url =new URL(actionUrl);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
/* 입력, 출력 허용, 캐시를 사용하지 마세요 */
// con.setReadTimeout(5 * 1000);
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 전송 방법 설정=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive") ;
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("enctype",
"multipart/form-data;boundary="+boundary);
/* DataOutputStream 설정 */
DataOutputStream ds =
new DataOutputStream(con.getOutputStream());
/*ds.writeBytes(twoHyphens +boundary + end);
ds.writeBytes(" Content -처리: form-data; " +
"name="file1";filename="" +
newName +""" + end);


ds.writeBytes( end ); */

/* 파일의 FileInputStream 가져오기 */
FileInputStream fStream = new FileInputStream(uploadFile);
/* 각 쓰기를 1024바이트로 설정 */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];

int length = -1;
/* 파일에서 버퍼로 데이터 읽기*/
while(( length = fStream.read(buffer)) != -1)
{
/* DataOutputStream에 데이터 쓰기*/
ds.write(buffer, 0, length);
}
// ds.writeBytes(end);
// ds.writeBytes(twoHyphens + 경계 + twoHyphens + end);

      /* 스트림 닫기 */
      fStream.close();
      ds.flush();
      
      
      /* 取得Response内容 */
     사기꾼 .getInputStream();
      int ch;
      StringBuffer b =new StringBuffer();
      while( ( ch = is.read() ) != -1 )
      {
        b. 추가( (char)ch );
      }
      /* 将Response显示于Dialog */
      showDialog(b.toString().trim());
      /* 关闭DataOutputStream */
      ds.close();
    }
    catch(예외 e)
    {
      showDialog(""+e);
    }
  }
  
  / * 显示Dialog의 메소드 */
  private void showDialog(String mess)
  {
    new AlertDialog.Builder(EX08_11.this).setTitle("Message")
     .setMessage(mess)
>> 🎜>     .show( );
  }
}

php代码

$data = file_get_contents('php://input');
$time = 날짜("YmdHis");

$rand = rand(0,100);

$filename = $_SERVER['DOCUMENT_ROOT'].'/image/'.$time.$rand.'.jpg';

while(file_exists($filename))

{
 $filename = $_SERVER['DOCUMENT_ROOT'].'/image/'.$time.rand(0,100).'.jpg'; 
}

echo $filename;
$handle = fopen($filename, 'w');
if ($handle)
{

  fwrite( $handle,$data);

  fclose($handle);

  echo "성공";
}

?>


以上就介绍了android 上传图 Pictures 到php服务器, 包括了方容, 希望对PHP教程有兴趣的朋友有所帮助.


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:PHP oci8 평가판다음 기사:PHP oci8 평가판