Android: jak przesłać plik. mp3 na serwer http?
Chcę przesłać plik. mp3 (tylko) z urządzenia na mój serwer.
Chcę przeglądać ścieżkę danych multimedialnych i wybrać dowolny plik mp3 i przesłać go.
Jak mogę to zrobić?
4 answers
Mój ostatni działający kod JAVA i PHP do przesłania pliku z karty SD Androida na mój własny serwer WWW.
Kod Java / Android:
private void doFileUpload() {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mypic.png";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
String urlString = "http://mywebsite.com/directory/upload.php";
try {
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
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);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + 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);
// close streams
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
Powiązany kod PHP, aby przejść na serwer (upload.php):
<?php
// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
chmod ("uploads/".basename( $_FILES['uploadedfile']['name']), 0644);
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
?>
Rzeczy do zapamiętania.
1) miałem " mypic.png " w katalogu głównym karty SD. Jeśli spojrzysz na urządzenie z Androidem przez Widok pamięci masowej USB, umieścisz plik w pierwszym katalogu, z którym się natkniesz.
2) USB PAMIĘĆ MASOWA MUSI BYĆ WYŁĄCZONA PRZEZ TELEFON! Lub po prostu całkowicie odłącz go od komputera, na którym piszesz kod, aby upewnić się, że tak jest.
3) musiałem utworzyć folder "uploads" w tym samym katalogu co mój plik php.
4) oczywiście musisz zmienić adres internetowy, który napisałem jako http://mywebsite.com/directory/upload.php być własną stroną internetową.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-26 11:33:55
Dzięki za dobrą sugestię Keaton.
Poukładałem trochę Kod Javy, więc jest gotowy do użycia i dodania wsparcia dla innych parametrów URL:
public class HttpMultipartUpload {
static String lineEnd = "\r\n";
static String twoHyphens = "--";
static String boundary = "AaB03x87yxdkjnxvi7";
public static String upload(URL url, File file, String fileParameterName, HashMap<String, String> parameters)
throws IOException {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream dis = null;
FileInputStream fileInputStream = null;
byte[] buffer;
int maxBufferSize = 20 * 1024;
try {
//------------------ CLIENT REQUEST
fileInputStream = new FileInputStream(file);
// open a URL connection to the Servlet
// Open a HTTP connection to the URL
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("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fileParameterName
+ "\"; filename=\"" + file.toString() + "\"" + lineEnd);
dos.writeBytes("Content-Type: text/xml" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
buffer = new byte[Math.min((int) file.length(), maxBufferSize)];
int length;
// read file and write it into form...
while ((length = fileInputStream.read(buffer)) != -1) {
dos.write(buffer, 0, length);
}
for (String name : parameters.keySet()) {
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(parameters.get(name));
}
// send multipart form data necessary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
} finally {
if (fileInputStream != null) fileInputStream.close();
if (dos != null) dos.close();
}
//------------------ read the SERVER RESPONSE
try {
dis = new DataInputStream(conn.getInputStream());
StringBuilder response = new StringBuilder();
String line;
while ((line = dis.readLine()) != null) {
response.append(line).append('\n');
}
return response.toString();
} finally {
if (dis != null) dis.close();
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-23 18:12:43
Uwaga jeśli skopiujesz i wkleisz powyższe kody PHP, każdy może przesłać złośliwy skrypt PHP na twój serwer i go uruchomić, zawsze pamiętaj o tym, sprawdź stronę serwera rozszerzeń z PHP istnieją tysiące przykładów tutaj iw internecie, jak to zrobić. Również dla dodatkowego bezpieczeństwa dodaj reguły do serwera apache, Nginx, aby dodać zawartość nagłówka-dyspozycja (jpg,png,gif,???) i nie parsować kodu PHP w folderze upload.
Na przykład w nxgin będzie to coś w rodzaju to...
#add header Content-Disposition
location ^~ /upload/pictures {
default_type application/octet-stream;
types {
image/gif gif;
image/jpeg jpg;
image/png png;
}
add_header X-Content-Type-Options 'nosniff';
if ($request_filename ~ /(((?!\.(jpg)|(png)|(gif)$)[^/])+$)) {
add_header Content-Disposition 'attachment; filename="$1"';
# Add X-Content-Type-Options again, as using add_header in a new context
# dismisses all previous add_header calls:
add_header X-Content-Type-Options 'nosniff';
}
}
#do NOT parse PHP script on the upload folder
location ~ \.php$ {
try_files $uri =404;
include /etc/nginx/fastcgi_params;
#if is the upload folder DO NOT parse PHP scripts on it
if ($uri !~ "^/upload/pictures") {
fastcgi_pass unix:/var/run/php-fastcgi/php-fastcgi.socket;
}
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-06 08:39:11
Wiem, że pytano o to jakiś czas temu. Próbowałem wdrożyć to samo i po wypróbowaniu wielu rozwiązań okazało się, że Kod @ Keaton ' s działa dla mnie, ale blokował mój UI (używam Android Studio 2.1.2), więc musiałem owinąć go w Asynktask.
Więc używając kodu @ Keaton mam to.
From my onClickListener ()
private View.OnClickListener btnUpload = new View.OnClickListener() {
@Override
public void onClick(View v) {
new doFileUpload().execute();
}
};
Następnie AsyncTask
public class doFileUpload extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
<Keaton's code>
return null;
}
}
Mam nadzieję, że to pomoże każdemu, kto ma ten sam problem, jaki miałem.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-07 21:48:59