Подскажите,отправляю на сервер текст + файл. Файл - фото. Нужные разрешения в манифесте прописаны.
Текст сервер получает а вот файл нет, в логах вижу данную запись:
D/ViewRootImpl: loadSystemProperties persistDebugEvent: false roDebugEvent: false
Код отправки через asynktask:
class UploadImage extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog
.show(MainActivity.this, "Please wait...", "uploading", false, false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String, String> param = new HashMap<String, String>();
param.put(KEY_NAME, name);
param.put(KEY_NASELPUNKT, naselpunkt);
param.put(KEY_STREET, street);
param.put(KEY_DOM, house);
param.put(KEY_EMAIL, e_mail);
param.put(KEY_MESAGES, message);
param.put(KEY_IMAGE, file);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
Класс request:
public class RequestHandler {
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
StringBuilder sb = new StringBuilder();
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
readHashMap(postDataParams);
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
while ((response = br.readLine()) != null){
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
public void readHashMap(HashMap<String, String> postDataParam) {
for (Map.Entry<String, String> stringStringEntry : postDataParam.entrySet()) {
Log.d("Ключ ",
stringStringEntry.getKey() + " значение " + stringStringEntry.getValue());
}
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
Получение файла:
private void openGalery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null &&
data.getData() != null) {
Uri filePath = data.getData();
// bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
file = getPath(filePath);
//imageViewUppload.setImageURI(filePath);
}
}
// Get Path of selected image
private String getPath(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
Код сервера:
<?php
if (isset ($_POST['contactFF'])) {
$to = "ukpmo"; // поменять на свой электронный адрес
$from = $_POST['contactFF'];
$subject = "Заполнена контактная форма с ".$_SERVER['HTTP_REFERER'];
$message = "Фамилия, собственное имя, отчество (если таковое имеется) либо инициалы гражданина: \n".$_POST['nameFF'].
"\nНаселенный пункт: ".$_POST['gorodFF'].
"\nУлица: ".$_POST['streetFF'].
"\nдом, квартира/офис: ".$_POST['homeFF'].
"\nEmail: ".$from.
"\nДата отправки сообщения: ".$date_today = date("d.m.Y H:i").
"\nИзложение сути обращения: ".$_POST['messageFF'];
$boundary = md5(date('r', time()));
$filesize = '';
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: " . $from . "\r\n";
$headers .= "Reply-To: " . $from . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";
$message="
Content-Type: multipart/mixed; boundary=\"$boundary\"
--$boundary
Content-Type: text/plain; charset=\"utf-8\"
Content-Transfer-Encoding: 7bit
$message";
for($i=0;$i<count($_FILES['fileFF']['name']);$i++) {
if(is_uploaded_file($_FILES['fileFF']['tmp_name'][$i])) {
$attachment = chunk_split(base64_encode(file_get_contents($_FILES['fileFF']['tmp_name'][$i])));
$filename = $_FILES['fileFF']['name'][$i];
$filetype = $_FILES['fileFF']['type'][$i];
$filesize += $_FILES['fileFF']['size'][$i];
$message.="
--$boundary
Content-Type: \"$filetype\"; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=\"$filename\"
$attachment";
}
}
$message.="
--$boundary--";
if ($filesize < 10000000) { // проверка на общий размер всех файлов. Многие почтовые сервисы не принимают вложения больше 10 МБ
mail($to, $subject, $message, $headers);
echo $_POST['nameFF'].', Ваше сообщение получено, спасибо!';
} else {
echo 'Извините, письмо не отправлено. Размер всех файлов превышает 10 МБ.';
}
}
?>
Код отправки текста + файла через пк,т.е через браузер, Все работает,т.е файл + текст сервер получает ,отправляю фото:
Request URL:http://dfg.by/wp-content/themes/reverie-master/contacts.php
Request Method:POST
Status Code:200 OK
Remote Address:148.114.138.185:80
Response Headers
view parsed
HTTP/1.1 200 OK
Date: Thu, 03 Nov 2016 17:39:00 GMT
Server: Apache
X-Powered-By: PHP/5.4.45
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html
Request Headers
view parsed
POST /wp-content/themes/reverie-master/contacts.php HTTP/1.1
Host: ukp.mogilev.by
Connection: keep-alive
Content-Length: 47014
Origin: http://ukp.mogilev.by
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryLgacUgprclABmklr
Accept: */*
DNT: 1
Referer: http://ukp.mogilev.by/elektronnye-obrashcheniya-grazhdan/
Accept-Encoding: gzip, deflate
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: _ym_uid=1478194399500303049; _ym_isad=1; _ym_visorc_28369546=w
Request Payload
------WebKitFormBoundaryLgacUgprclABmklr
Content-Disposition: form-data; name="nameFF"
тест
------WebKitFormBoundaryLgacUgprclABmklr
Content-Disposition: form-data; name="gorodFF"
тест
------WebKitFormBoundaryLgacUgprclABmklr
Content-Disposition: form-data; name="streetFF"
тест
------WebKitFormBoundaryLgacUgprclABmklr
Content-Disposition: form-data; name="streetFF"
тест
------WebKitFormBoundaryLgacUgprclABmklr
Content-Disposition: form-data; name="streetFF"
q@tut.by
------WebKitFormBoundaryLgacUgprclABmklr
Content-Disposition: form-data; name="messageFF"
тест
------WebKitFormBoundaryLgacUgprclABmklr
Content-Disposition: form-data; name="fileFF[]"; filename="3.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryLgacUgprclABmklr
Content-Disposition: form-data; name="fileFF[]"; filename=""
Content-Type: application/octet-stream
------WebKitFormBoundaryLgacUgprclABmklr--
Частный дом престарелых в Киеве: комфорт, забота и профессиональный уход
Здравствуйте! я начинающий прогер и не могу разобраться помогите пожалуйстаЕсть NavigationView и несколько фрагмент страничек
Помогите разобратьсяИнтересует, почему если добавлять панель на фрейм , указывая BorderLayout
Добрый день, пытаюсь сменить у jar файла иконкуДля этого использую данную конструкцию