我尝试了以下链接:
https://stackoverflow.com/a/35465318/787399
但我从未收到onSuccess回调。
更多:当我上传多个文件[图像]时,只有一个文件被上传,其他文件都是空白的。
更多:当使用通常的HTTPClient API时,我在另一端得到了重复的文件,因此我从loopj切换到了这个库。然而,这个图书馆也有它的一系列问题。
以下是帮助您的代码。
public class uploadFiles extends AsyncTask<Void, Void, String> {
private final ProgressDialog dialog = new ProgressDialog(
PtoPPostActivity.this);
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
@Override
protected String doInBackground(Void... params) {
String result=uploadFile(""); // inside the method paste your file uploading code
return result;
}
protected void onPostExecute(String result) {
// Here if you wish to do future process for ex. move to another activity do here
if (dialog.isShowing()) {
dialog.dismiss();
}
showDialog(PtoPPostActivity.this,result);
}
}
public String uploadFile(String req) {
// TODO Auto-generated method stub
String serverResponseMessage = "";
String response_return = "";
Log.d("first str is:", req);
URL imageUrl = null;
try {
imageUrl = new URL(Constant.WEBSERVICE_URL); // get WebService_URL
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "---------------------------14737809831466499882746641449";
// generating byte[] boundary here
HttpURLConnection conn = null;
DataOutputStream outputStream = null;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
int serverResponseCode;
conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// json String request
outputStream = new DataOutputStream(conn.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name="json"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
outputStream.writeBytes("Content-Length: " + req.length() + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(req + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
// image
Log.i("images path==>", "" + imageArry); // get photo
// local path
for (int i = 0; i < imageArry.size(); i++) {
try {
String filePath = imageArry.get(i).get("uploadedPath");
Log.d("filePath==>", imageArry.get(i).get("uploadedPath") + "");
//////////////////////////////////////////////////
// Bitmap original = BitmapFactory.decodeFile(mFileTemp.getPath());
Bitmap original = BitmapFactory.decodeFile(filePath);
if (original != null) {
Bitmap newBitmap = original;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapdata = stream.toByteArray();
File cacheDir = PtoPPostActivity.this.getCacheDir();
File f = new File(cacheDir, "temp" + i + ".jpeg");
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
FileInputStream fileInputStream = new FileInputStream(f);
String lastOne = "temp";
/////////////////////////////////////////////
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: attachment; name="imagePath" + i + ""; filename=" + lastOne + i + ".jpeg" + lineEnd); // pass key & value of photo
outputStream.writeBytes("Content-Type: application/octet-stream" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // photo size bytes
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);
Log.d("posttemplate", "connection outputstream size is " + outputStream.size());
fileInputStream.close();
}
} catch (OutOfMemoryError o) {
continue;
}
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response1 = new StringBuffer();
while ((line = rd.readLine()) != null) {
response1.append(line);
response1.append('r');
}
rd.close();
response_return = response1.toString();
Log.d("posttemplate", "server response code " + serverResponseCode);
Log.d("posttemplate", "server response message "
+ serverResponseMessage);
outputStream.flush();
outputStream.close();
conn.disconnect();
} catch (MalformedURLException e) {
Log.d("posttemplate", "malformed url", e);
// Toast.makeText(getApplicationContext(),e.toString(),
// Toast.LENGTH_LONG).show();
// TODO: catch exception;
} catch (IOException e) {
Log.d("posttemplate", "ioexception", e);
// Toast.makeText(getApplicationContext(),e.toString(),
// Toast.LENGTH_LONG).show();
// TODO: catch exception
}
Log.d("response--->", "****" + response_return);
global_response = response_return;
return response_return;
}