Answer the question
In order to leave comments, you need to log in
How to send files using HttpUrlConnection?
Good day to all!
I could find very little sensible information on the net, I hope someone can explain something to me.
And so, there is a mobile application, you need to send a file from it to the server where php will receive it.
There are no problems on the php side, but on the client side I don’t understand where the legs grow from.
From those snippets of information and code examples, I was able to assemble and tidy up the following function
static String SendFilePOST(String address, String data, String FilePath) {
String result = "";
try {
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
File file = new File(FilePath);
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Вот до сюда всё логично
String boundary = UUID.randomUUID().toString();
// Что такое boundary и зачем оно нужно? Я понимаю, что это граница, но граница чего? Данных?
//нужно ли мне это как-то особенным образом обрабатывать на стороне php?
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream request = new DataOutputStream(conn.getOutputStream());
//если boundary - это граница, то зачем мне тут ещё "--"?
request.writeBytes("--" + boundary + "\r\n");
request.writeBytes("Content-Disposition: form-data; name=\"description\"\r\n\r\n");
request.writeBytes("Какое-то описание фала\r\n");
//на сколько я могу судить, здесь я задаю значение переменной description
//которую смогу прочитать в $_POST['description']
//Если я понимаю правильно, тогда зачем два переноса строк?
//и почему дальше я объявляю переменную file, но сразу на ней идёт filename
//а содержимое файла от его имени отделено только переносами строк?
request.writeBytes("--" + boundary + "\r\n");
request.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n\r\n");
//добавление файла
FileInputStream fileInputStream = new FileInputStream(file);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
request.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
//конец добавления файла
request.writeBytes("\r\n");
request.writeBytes("--" + boundary + "--\r\n");
request.flush();
int respCode = conn.getResponseCode();
switch(respCode) {
case 200:
result = "ok";
break;
case 301:
case 302:
case 307:
//handle redirect - for example, re-post to the new location
break;
default:
//do something sensible
}
} catch (Exception e) {
return e.getMessage();
}
return result;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question