场景: 我正在尝试通过服务中的 HttpURLConnection 发送一些 POST 数据(有进度更新)。 我从图库中抓取一张图片,然后将它发送到带有 2 个参数的 php 服务器; invnum 和密码。
注意: 如果我通过 HttpClient 方法执行此操作,则会在服务器中发送和接收参数和图像,但我无法跟踪上传进度。我看到一些与自定义多部分实体相关的代码,我想尽可能避免引用库
我在 SO 中研究了很多相关问题,但似乎找不到解决方案。以下是我服务中的当前代码。
protected void onHandleIntent(Intent intent) {
String invnum = intent.getStringExtra("invnum");
String uploadURL = intent.getStringExtra("uploadURL");
String imageURI = intent.getStringExtra("imageURI");
uri = Uri.parse(imageURI);
String pass = "password";
//get the actual path of the image residing in the phone
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
//check url
try {
File file = new File(picturePath);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fileInputStream.read(bytes);
fileInputStream.close();
String fileName = file.getName();
URL url = new URL(uploadURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setChunkedStreamingMode(1024);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)");
connection.setRequestProperty("image", fileName);
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
//send multipart form data (required) for file
outputStream.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\"" + fileName + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
//outputStream.writeBytes("Content-Type: " + URLConnection.guessContentTypeFromName(fileName) + lineEnd);
//outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
//outputStream.writeBytes("Content-Type: application/octet-stream" + lineEnd);
outputStream.writeBytes("Content-Length: " + file.length() + lineEnd);
outputStream.writeBytes(lineEnd);
int bufferLength = 1024;
for (int i = 0; i < bytes.length; i += bufferLength) {
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress" ,(int)((i / (float) bytes.length) * 100));
receiver.send(UPDATE_PROGRESS, resultData);
if (bytes.length - i >= bufferLength) {
outputStream.write(bytes, i, bufferLength);
} else {
outputStream.write(bytes, i, bytes.length - i);
}
}
//end output
outputStream.writeBytes(lineEnd);
//write more parameters other than the file
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
//outputStream.writeBytes(twoHyphens + boundary + lineEnd); //less twohyphens
outputStream.writeBytes("Content-Disposition: form-data; name=\"invnum\"" + lineEnd);
//outputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
//outputStream.writeBytes("Content-Length: " + invnum.length() + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(invnum + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"pass\"" + lineEnd);
//outputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
//outputStream.writeBytes("Content-Length: " + pass.length() + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(pass + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress", 100);
receiver.send(UPDATE_PROGRESS, resultData);
outputStream.flush();
outputStream.close();
//input ignored for now
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
运行应用程序时,进度反射(reflect)得很好,但在检查我的服务器时,根本没有文件上传。实际上服务器没有发送或接收数据。有谁知道可能导致此问题的原因是什么?下面是我的服务器代码。
$pass = $_POST['pass'];
$invnum = $_POST['invnum'];
$image = $_POST['image'];
if ($pass == 'password') {
//do something
}
更新: 首先,我从 HTTPURLConnection 收到 404 错误。我的网址看起来像“http://www.xyz.com/upload.php”。 更新前一句,通过删除“setChunkedStreamingMode”,我能够成功将参数上传到服务器但不是图像!我很接近!
最佳答案
终于成功了...
行“connection.setChunkedStreamingMode(1024);”导致问题。删除后,参数和文件上传成功。还有一个小问题,上传进度不准确。返回的进度实际上是缓冲区被填满,即使是 3MB 的图像也几乎是瞬时的。进度到100后,文件仍在后台上传。猜猜这将是另一个问题。
关于php - 通过 HttpURLConnection 将参数和图像上传到 PHP 服务器 (Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19262817/