I created some code to handle basic file upload from a java client to a php server, but I’m having some issues with the naming and directory creation. Here is the important parts of the code:
The method I use to upload the file:
public static void uploadWithInfo(Uri uri, String title, String artist, String description) {
try {
String path = uri.getPath();
File file = new File(path);
URL url = new URL("http://**********/upload.php?title="+title+"&artist="+artist+"&description="+description);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream os = connection.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int totalbytes = bis.available();
for(int i = 0; i < totalbytes; i++) {
os.write(bis.read());
}
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String serverResponse = "";
String response = "";
while((response = reader.readLine()) != null) {
serverResponse = serverResponse + response;
}
reader.close();
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
It’s just supposed to upload an audio file. The user inputs the artist, title, and a very short description if necessary. The actual file is uploaded just fine so I don’t think any more java is necessary. Here is the code on the php end:
<?php
$uploadBase = "music/";
$uploadFolder = $_GET['artist']+"/";
$uploadFileName = $_GET['title'];
$uploadFileDescription = $_GET['description'];
$uploadPath = $uploadBase.$uploadFolder.$uploadFileName."%%D%%=".$uploadFileDescription.".mp3";
if(!is_dir($uploadBase)) {
mkdir($uploadBase);
}
if(!is_dir($uploadFolder)) {
mkdir($uploadFolder);
}
$incomingData = file_get_contents('php://input');
if(!$incomingData) {
die("No data.");
}
$fh = fopen($uploadPath, 'w') or die("Error opening path.");
fwrite($fh, $incomingData) or die("Error writing file.");
fclose($fh) or die("Error closing shop.");
echo "Success!";
?>
So I get all of the inputted values for title, artist, and description. Then I create 2 directories if they don’t already exist: one for music and one for the artist the uploader input. Then I create a path of base(music)/folder(artist)/filename(title)”code to let me parse description”(%%D%%).mp3.
So a song Billie Jean by Michael Jackson with a description “favorite” should have a path of
music/Michael Jackson/Billie%20Jean%%D%%favorite.mp3
What I get however, is:
music/0Billie%%D%%=
The directory for artist is not created, there is a weird 0 before the title (which only includes the first word), and the description doesn’t show.
I don’t really know where I went wrong, can anyone give me some insight? Thank you.
Turns out it was a stupid error with some related php code. Sorry to trouble you all.