내 안드로이드 장치에서 파일을 PHP 서버로 업로드하려고합니다. 같은 질문을 가진 실이 있지만 다른 방법을 사용하고 있습니다. 내 Android 측 코드가 제대로 작동하고 오류 메시지가 표시되지 않지만 서버에서 파일을 수신하지 않습니다. 여기에 내 샘플 코드가 있습니다. 온라인으로 찾았습니다. 아파치가 실행안드로이드에서 PHP 서버로 사진 업로드
<?php
$target_path = "uploads/";
$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!";
}
?>
을 다음과 같이
import java.io.FileInputStream;
import android.app.Activity;
import android.os.Bundle;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
public class uploadfile extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
doFileUpload();
}
private void doFileUpload(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String exsistingFileName = "/sdcard/def.jpg";
// Is this the place are you doing something wrong.
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://192.168.1.6/index.php";
try
{
//------------------ CLIENT REQUEST
Log.e("MediaPlayer","Inside second Method");
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ exsistingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e("MediaPlayer","Headers are written");
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0){
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("MediaPlayer","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream (conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null)
{
Log.e("MediaPlayer","Server Response"+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
}
}
내 PHP는 서버 측 코드입니다. 서버를 실행할 때이 오류 메시지가 나타납니다. 파일을 업로드하는 중 오류가 발생했습니다. 다시 시도하십시오. 이클립스에서 로그 데이터를 확인하고 내가 소켓 문제라고 생각하지만 확실하지 않습니다. 누군가가 해결책을 안다면 도와주세요.
11-28 05:37:55.310: DEBUG/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol
변경된 태그
교체 -이와 아무로 표시되지 않습니다 PHP - 당신은 전통적인 브라우저를 사용하여 간단한 테스트 페이지로 이것을 확인할 수 있어야합니다. – symcbean
하지만이 PHP 코드는 PHP에있는 PHP 코드라고 생각합니다. – SilentCoder
이 코드를 시도했는데 POST 요청에서 아무 파일도 전송되지 않는다고 말할 수 있습니다. var_dump ($ _ FILES);를 사용하여 테스트했습니다. – Richard