В моем приложении мне нужно реализовать загрузку изображений, текстовые файлы ZIP-архивов и файл PDF. Все отлично для img \ txt \ zip \ pdf, но когда я выбираю файл размером более 2 мб, он не загружается. следующий мой код.Файлы размером более 2 МБ не загружаются на сервер
public int uploadFile(String sourceFileUri)
{
try
{
StrictMode.ThreadPolicy policy= new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile())
{
title=filename+"";
generateNotification(title, "Upload Failed..File Not Found");
}
else
{
FileInputStream fileInputStream = new FileInputStream(sourceFile);
String upLoadServerUri = "http://xx.xx.xx.xxx:xx/phpwebservice/upload.php";
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", filename);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ filename + "\"" + lineEnd);
dos.writeBytes(lineEnd);;
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
if(serverResponseCode == 200)
{
status = true;
}
else
{
title=filename+"";
generateNotification(title, "File Not Uploaded");
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
}
}
catch (final MalformedURLException ext)
{
title=filename+"";
generateNotification(title, "File Not Uploaded");
}
catch (final Exception etx)
{
title=filename+"";
generateNotification(title, "File Not Uploaded");
}
//dialog.dismiss();
return serverResponseCode;
}
Просьба представить решение:
- как загружать файлы размером более 2Мб с помощью этого метода?
Мой PHP код на стороне веб-сервис:
<?php
$file_path = "a/";
$file_path = $file_path . basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path))
{
echo "success";
}
else
{
echo "fail";
}
?>
Проблема может быть на стороне сервера. Проверьте разрешения на сервере. –
Для файлов pdf попробуйте добавить 'dos.writeBytes (« Content-Type: application/pdf »+ lineEnd);' после строки Content-Disposition. Максимальный размер загрузки 2 МБ, который вы должны настроить на стороне веб-сервера. – greenapps
Попробуйте выполнить поиск в PDF-файле (откройте его как текст в каком-то редакторе), возможно, он содержит в себе символы «*****», поэтому серверу угрожает эта часть файла в качестве конца. – OleGG