Я хочу загрузить файл на php-сервер. я мог загрузить файл с ниже способом:загрузить файл, используя метод post в android
curl -i -X POST -F [email protected] http://something/sth
и после этого я могу загрузить с помощью браузера.
, но при загрузке файла с использованием кода java я не смог загрузить с помощью браузера.
URL url = new URL(mUrl);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag = "fSnd";
Log.e(Tag, "Starting Http File Sending to URL");
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
bytes);
// Open a HTTP connection to the URL
HttpURLConnection 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);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"title\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes("File1");
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"description\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes("File2");
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ "File3.jpg" + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag, "Headers are written");
byte data[] = new byte[1024 * 2];
int count = 0;
while ((count = byteArrayInputStream.read(data)) != -1) {
mSoFarLength += count;
Log.d("FFF", "count : " + count + " mSoFarLength : "
+ mSoFarLength + " mTotalLength : " + mTotalLength);
dos.write(data, 0, count);
mProgress = ((mSoFarLength * 100)/mTotalLength);
for (LocalTransmitterListener baseTransmitterListener : baseTransmitterListeners) {
baseTransmitterListener.onUpdateProgress(mProgress);
}
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
byteArrayInputStream.close();
dos.flush();
Log.e(Tag,
"File Sent, Response: "
+ String.valueOf(conn.getResponseCode()));
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String s = b.toString();
Log.i("Response", s);
dos.close();
Мне нужно загрузить индикатор прогресса. Спасибо за ваш код, но в java upload part, где я могу загрузить мои данные о ходе выполнения? –