업로드에 관련하여 질문드립니다.
httpURLConnection를 이용하여 php서버쪽에 파일을 올리고 싶은데요( 어떤 형식의 파일이든 관련없음 )
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button uploadBtn = (Button)findViewById(R.id.uploadBtn);
uploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
doFileUpload();
}
});
}
private void doFileUpload() {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmp_1436920364055.jpg";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 10 * 1024 * 1024;
String responseFromServer = "";
String urlString = "http://localhost:8080/phpServer/Server.php";
try {
System.out.println("errorpoint:1");
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName)); //error point **
System.out.println("errorpoint:2");
// open a URL connection to the Servlet
URL url = new URL(urlString);
System.out.println("errorpoint:3");
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
System.out.println("errorpoint:4");
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
System.out.println("errorpoint:5");
conn.setRequestMethod("POST");
System.out.println("errorpoint:6");
conn.setRequestProperty("Connection", "Keep-Alive");
System.out.println("errorpoint:7");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
System.out.println("errorpoint:8");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// 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("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
}
php 소스입니다 ( 이부분은 인터넷에서 그대로 옮겼습니다 )
<?php
/**
* Created by PhpStorm.
* User: user
* Date: 2015-07-15
* Time: 오후 2:54
*/
echo "phpServer";
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$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";
chmod ("uploads/".basename( $_FILES['uploadedfile']['name']), 0644);
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
?>
아무쪼록 부족한 초보개발자를 도와주십사합니다 ㅎㅎ;