我有一个应用程序在Android女巫拍摄一张照片,需要将其uppad到服务器与PHP。发送数据从Java(Android)到PHP与POST
起初没有问题,我能够上传它,但现在我需要传递图片上传到服务器的路径。当我尝试发送两个值时会出现问题。
我使用下面的代码:
private void httpPostFileUpload(String fpath, String uPath){
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
//Path where to upload
String uploadPath = uPath;
String pathToOurFile = fpath;
Log.v("file path",fpath.toString());
String urlServer = "http://leojg.alwaysdata.net/tests/androidConnect/handle_upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String fname = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try
{
File f = new File(pathToOurFile);
fname = f.getName();
FileInputStream fileInputStream = new FileInputStream(f);
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
Log.d("path file", pathToOurFile);
Log.d("path up", uploadPath);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.d("amanda", "upload async finished, server response : " + serverResponseMessage);
fileInputStream.close();
fileInputStream = null;
outputStream.flush();
outputStream.close();
outputStream = null;
f= null;
parent.invokeJs("pictureUploadEnded('" + fname + "')");
this.delete(fpath);
}
catch (Exception ex)
{
Log.d("amanda", "exception uploading image : " + ex.getMessage());
}
}
我敢肯定,这个问题是在这条线
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\"" + lineEnd);
这是一个使后车身。我不知道在哪里attrach uploadPath
和问题是什么 – Ibu
我如何发送两个或更多的POST值。 –
看看... http://stackoverflow.com/questions/2017414/post-multipart-request-with-android-sdk –