android upload image file into PHP server - php

I took this code on Internet. I can upload image file to Server successful. However, the image files cannot be opened. I think the content of the files has problem after uploading. Can anybody help me please? Thank you very much
public static void put(String targetURL, File file, String username, String password) throws Exception {
String BOUNDRY = "==================================";
HttpURLConnection conn = null;
try {
// Make a connect to the server
URL url = new URL(targetURL);
conn = (HttpURLConnection) url.openConnection();
if (username != null) {
String usernamePassword = username + ":" + password;
//String encodedUsernamePassword = Base64.encodeBytes(usernamePassword.getBytes());
String encodedUsernamePassword = String.valueOf(Base64.encodeBase64(usernamePassword.getBytes()));
conn.setRequestProperty ("Authorization", "Basic " + encodedUsernamePassword);
}
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDRY);
DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
dataOS.writeBytes("--");
dataOS.writeBytes(BOUNDRY);
dataOS.writeBytes("\n");
dataOS.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\"; fileName=\"" + file.getName() +"\"" + "\n");
dataOS.writeBytes("\n");
dataOS.writeBytes(new String(getBytesFromFile(file)));
dataOS.writeBytes("\n");
dataOS.writeBytes("--");
dataOS.writeBytes(BOUNDRY);
dataOS.writeBytes("--");
dataOS.writeBytes("\n");
dataOS.flush();
dataOS.close();
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
throw new Exception(String.format("Received the response code %d from the URL %s", responseCode, url));
}
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
int bytesRead;
while((bytesRead = is.read(bytes)) != -1) {
baos.write(bytes, 0, bytesRead);
}
byte[] bytesReceived = baos.toByteArray();
baos.close();
is.close();
String response = new String(bytesReceived);
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, Math.min(bytes.length - offset, 512*1024))) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
And the bellow is my code in PHP:
$target = "/upload/";
$target = $target . basename( $_FILES['fileToUpload']['name']) ;
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target)) {
echo "The file ". basename( $_FILES['fileToUpload']['name']). " has been uploaded";
$result['login'] = true;
}else {
$result['login']=false;
echo "Sorry, there was a problem uploading your file.";
}
$json = json_encode($result, JSON_PRETTY_PRINT);
print_r($json);

Maybe problem occur when you set Content-Type, try remove this
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDRY);

Related

Uploading images from app to server using PHP

I have a cross platform app built using Monaca/Onsen UI and AngularJS.
The app allows users to take images (photos) and this is working as intended.
Next, I want to upload the images to my server for storage and future use.
I have the app image capture working as intended and I have implemented a PHP solution on the server that appears to be working, but I cant seem to see the images.
My app code for capture and upload looks as follows (at the moment I just access the image library and select images for testing - rather than capturing them - but both solutions working):
$scope.takePicture = function getImage() {
navigator.camera.getPicture(uploadPhoto, function (message) {
alert('get picture failed');
}, {
quality: 100, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
});
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://mysite/public/api/savephotos.php", function (result) {
alert("Success: " + JSON.stringify(result)); // Success: {"bytesSent":42468,"responseCode":200,"response":"","objectId":""}
}, function (error) {
alert("Fail: " + JSON.stringify(error));
}, options);
}
From the success response it seems that images are being sent, but when I check the folder where the images are supposed to be saved to (C:\xampp\htdocs\public\api\upload), the folder is empty. The server side details are Sximo template using Laravel framework hosted on AWS.
The PHP code that handles the server side saving looks as below:
<?php
// Connect to Database
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'myDB';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Allow Headers
header('Access-Control-Allow-Origin: *');
$new_image_name = urldecode($_FILES["file"]["name"]).".jpg";
// Move files into upload folder
move_uploaded_file($_FILES["file"]["tmp_name"], 'C:\xampp\htdocs\public\api\upload'.$new_image_name);
mysqli_close($mysqli);
However, the C:\xampp\htdocs\public\api\upload is empty - with no images sent to it. I do have a file called uploadimage that has been sent to the directory *C:\xampp\htdocs\public\api* that appears to be updated with each test - but this is a empty (0kb) file.
Where am I going wrong with this?
This is the asynktask that I use to send image from the gallery app to server
public static class requestPostReportPhoto extends AsyncTask<String, Void, String> {
Bitmap image;
String JSON_STRING;
#Override
protected void onPreExecute(){
String fileUrl = Environment.getExternalStorageDirectory()+"/"+Environment.DIRECTORY_DCIM+"/"+"albumName"+"/"+"photoName";
image = BitmapFactory.decodeFile(fileUrl);
}
#Override
protected String doInBackground(String... params) {
String fileUrl = Environment.getExternalStorageDirectory()+"/"+Environment.DIRECTORY_DCIM+"/"+"albumName"+"/"+"photoName";
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
HttpURLConnection connection = null;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String response = "Error";
String urlString = "yourUrlServer";
try {
File file = new File(fileUrl);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); // Allow Inputs
connection.setDoOutput(true); // Allow Outputs
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.addRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);
dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + "PHOTONAME" + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.d("MediaPlayer", "Headers are written");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
StringBuilder responseSB = new StringBuilder();
int result = connection.getResponseCode();
BufferedReader br;
// 401 - 422 - 403 - 404 - 500
if (result == 401 || result == 422 || result == 403 || result == 404 || result == 500)
{
br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
else {
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
}
while ( (JSON_STRING = br.readLine()) != null)
responseSB.append(JSON_STRING+ "\n");
Log.d("MediaPlayer","File is written");
fileInputStream.close();
dos.flush();
dos.close();
br.close();
response = responseSB.toString().trim();
} catch (IOException ioe) {
Log.d("MediaPlayer", "error: " + ioe.getMessage(), ioe);
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.d("SERVER RESPONSE ->",result)
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}

PHP can not find files in windows

I have build a server use PHP based on WAMP Server on my windows 10 computer. what I want to do is when I send a GET request, the show_files.php should return a JSON object to me. The JSON object contains file names in path F:\NetEaseMusic\download on my computer. Then I use a file name to send a POST request to download_file.php and it returns a data stream so that I can download file. When I use HttpURLConnection, everything works well. However, when I try send the POST request use socket, download_file.php can get the file_name param, but it can not find the target file in F:\NetEaseMusic\download. I show the code.
this is
this is download_file.php
<?php
if(empty($_POST["file_name"]))
{
echo "NO_FILE_NAME\n";
print_r($_POST);
exit();
}
$path = iconv("utf-8", "GB2312","F:\\NetEaseMusic\\download\\".$_POST["file_name"]);
//$path = "F:\\NetEaseMusic\\download\\".$_POST["file_name"];
if (!file_exists ( $path )) {
echo "FILE_NOT_FOUND\n";
echo "F:\\NetEaseMusic\\download\\".$_POST["file_name"]."\n";
print($path);
exit ();
}
$file_size = filesize($path);
//header("Content-type: application/octet-stream");
//header("Accept-Ranges: bytes");
//header("Accept-Length:".$file_size);
//header("Content-Disposition: attachment; filename=".$path);
$file = fopen($path, "r");
while(!feof($file))
{
echo fread($file, 1024);
}
exit();
?>
this is my Client code which to download file. First of all I build a HTTP POST request,
private void downloadFileBySocket(String urlString, String fileName)
{
try{
StringBuilder sb = new StringBuilder();
String data = URLEncoder.encode("file_name", "utf-8") + "=" + URLEncoder.encode(fileName, "utf-8") + "\r\n";
//String data = "&file_name="+fileName;
sb.append("POST " + urlString + " HTTP/1.1\r\n");
sb.append("Host: 10.206.68.242\r\n");
sb.append("Content-Type: application/x-www-form-urlencoded\r\n");
sb.append("Content-Length: " + data.length() + "\r\n");
sb.append("\r\n");
sb.append(data + "\r\n");
//sb.append( URLEncoder.encode("file_name", "utf-8") + "=" + URLEncoder.encode(fileName, "utf-8") + "\r\n");
System.out.println(sb.toString());
URL url = new URL(urlString);
Socket socket = new Socket(url.getHost(), url.getPort());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
writer.write(sb.toString());
writer.flush();
File file = new File("./" + fileName);
DataOutputStream out = null;
DataInputStream in = null;
try{
out = new DataOutputStream(new FileOutputStream(file));
in = new DataInputStream(socket.getInputStream());
byte[] buffer = new byte[1024];
int readBytes = 0;
while((readBytes = in.read(buffer)) != -1)
{
out.write(buffer, 0, readBytes);
}
out.flush();
}catch (Exception e1)
{
e1.printStackTrace();
}finally {
try{
if(in != null)
{
in.close();
}
if(out != null)
{
out.close();
}
}catch (Exception e2)
{
e2.printStackTrace();
}
}
socket.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
and my main[] method
public static void main(String[] args)
{
SocketTest socketTest = new SocketTest();
socketTest.downloadFileBySocket(SocketTest.downloadFileUrl, "小胡仙儿 - 【二胡】霜雪千年.mp3");
}
Simple way:
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("example.com/myfile.txt", #"c:/myfile.txt");

Saving a file inside the application's memory

I am trying to download a file from a php get url that has username and password. My code doesn't show any errors and the progress bar shows me that the file is downloaded but when I try to print the list inside the Log I cannot see the file. What am I doing wrong?
That's the code inside the doInBackground section in the AsyncTask which I have called inside the onCreate and have put the url inside the parameters.
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try{
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(context.getFilesDir()+"video.m3u");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1){
total = total + count;
if (fileLength > 0){
publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
}catch (Exception e){
return e.toString();
}finally {
try{
if (output != null){
output.close();
}
if (input != null){
input.close();
}
}catch (IOException ignored){
}
if (connection != null){
connection.disconnect();
}
}
return "";
}
In the onPostExecute section I have written this code
if (result.equals("")){
String path = context.getFilesDir().toString();
Log.d("Files", "Path: "+ path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: " + files.length);
for (int i = 0; i<files.length; i++){
Log.d("Files", "File Name: " + files[i].getName());
}
}
But the only thing that I get printed is this:
D/Files: Path: /data/data/my.app.package/files
D/Files: Size: 1
D/Files: File Name: instant-run
I can't see the file that has been downloaded.
I think the problem is this line
output = new FileOutputStream(context.getFilesDir()+"video.m3u");
context.getFilesDir() doesn't return String, it's File object you need to do this
output = new FileOutputStream(context.getFilesDir()..getAbsolutePath()+"/video.m3u");
The file path you are saving to is wrong. Right now you are saving to
output = new FileOutputStream(context.getFilesDir()+"video.m3u");
it needs to be output = new FileOutputStream(context.getFilesDir().getAbsolutePath()+"/video.m3u");
Hopes this helps.

How to upload an image from android to php using asynctask

everyone. I am stuck on this project I am working on. I want to be able to upload an image from the android gallery, encode that image to a base64 string and send to PHP web service, as a get variable, then decode the image from the other end and do with it as I wish.
So far I am able to select the image, from the gallery and even encode to base64 string and storing in android preference.
The problem is, I think that not all the string is being sent to the PHP service (Some is truncated).
Why do I think so? My Log.d showed me different strings when dumped at different locations.
The code that gets the image and encodes is:-
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Please select a file"),1);
}
private String onSelectFromGalleryResult (Intent data) {
if (data != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver() , data.getData()) ;
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream() ;
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream) ;
byte[] imageBytes = byteArrayOutputStream.toByteArray() ;
Log.d ("Selected Image Gallery" , Base64.encodeToString(imageBytes, Base64.DEFAULT)) ;
return Base64.encodeToString (imageBytes, Base64.DEFAULT) ;
} else {
return null ;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
SharedPreferences sharedPreferences = getContext().getSharedPreferences("MyOnActivityResultPref" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit() ;
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
/*Here we handle the image gotten from the gallery*/
String encodedGalleryImage = onSelectFromGalleryResult(data);
editor.putString("userEncodedGalleryImage" , encodedGalleryImage);
} else if (requestCode == 0) {
/*Here we handle the image that was take using the camera*/
}
editor.apply();
}
}
Here we call the asynctask class
private void callAsynctask () {
SharedPreferences sp = getContext().getSharedPreferences("MyOnActivityResultPref" , Context.MODE_PRIVATE);
String userQuestionAttachement = sp.getString("userEncodedGalleryImage" , "") ;
Log.d("callingEncodedImage" , userQuestionAttachement) ;
}
The problem I have is that the log from Log.d ("Selected Image Gallery" , Base64.encodeToString(imageBytes, Base64.DEFAULT)) ; is different from Log.d("callingEncodedImage" , userQuestionAttachement) ;
There both have same beginning, but different endings. I expect to see the same characters.
Can someone please help me sort it out?
In Android,
new UploadFileAsync().execute("");
private class UploadFileAsync extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String sourceFileUri = "/mnt/sdcard/abc.png";
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()) {
try {
String upLoadServerUri = "http://website.com/abc.php?";
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
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("bill", sourceFileUri);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
+ sourceFileUri + "\"" + 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) {
// messageText.setText(msg);
//Toast.makeText(ctx, "File Upload Complete.",
// Toast.LENGTH_SHORT).show();
// recursiveDelete(mDirectory1);
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (Exception e) {
// dialog.dismiss();
e.printStackTrace();
}
// dialog.dismiss();
} // End else block
} catch (Exception ex) {
// dialog.dismiss();
ex.printStackTrace();
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
In Php,
<?php
if (is_uploaded_file($_FILES['bill']['tmp_name'])) {
$uploads_dir = './';
$tmp_name = $_FILES['bill']['tmp_name'];
$pic_name = $_FILES['bill']['name'];
move_uploaded_file($tmp_name, $uploads_dir.$pic_name);
}
else{
echo "File not uploaded successfully.";
}
?>
To upload image using Multipart follow the following steps:
Download httpmime.jar file and add it in your libs folder.
Download http client.jar file and add it in your libs folder.
Call the following method either from a background thread or an AsyncTask.
public void executeMultipartPost() throws Exception {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"YOUR SERVER URL");
ByteArrayBody bab = new ByteArrayBody(data, "YOUR IMAGE.JPG");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("IMAGE", bab);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
}
}

Image/Video/Audio Succeed in Upload from Android to PHP but Can't open them - damaged/corrupted

I make this HTTP POST request in my Android application:
private final String delimiter = "--";
private final String boundary = "SwA"
+ Long.toString(System.currentTimeMillis()) + "SwA";
private final String charset = "UTF-8";
private final String lineSpace = "\r\n";
private final String domain = (domain);
private HttpURLConnection configureConnectionForMultipart(String url)
throws MalformedURLException, IOException {
HttpURLConnection con = (HttpURLConnection) (new URL(url))
.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary="
+ boundary);
return con;
}
private void addFormPart(String paramName, String value, DataOutputStream os)
throws IOException {
os.writeBytes(lineSpace + delimiter + boundary + lineSpace);
os.writeBytes("Content-Disposition: form-data; name=\"" + paramName
+ "\"" + lineSpace);
os.writeBytes("Content-Type: text/plain; charset=" + charset
+ lineSpace);
os.writeBytes(lineSpace + value + lineSpace);
os.flush();
}
private void addFilePart(String paramName, File data, DataOutputStream os)
throws IOException {
os.writeBytes(lineSpace + delimiter + boundary + lineSpace);
os.writeBytes("Content-Disposition: form-data; name=\"" + paramName
+ "\"; filename=\"" + data.getAbsolutePath() + "\"" + lineSpace);
os.writeBytes("Content-Type: application/octet \r\n");
os.writeBytes("Content-Transfer-Encoding: binary" + lineSpace);
// os.writeBytes(lineSpace);
os.flush();
FileInputStream fis = new FileInputStream(data);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.writeBytes(lineSpace);
os.flush();
fis.close();
}
private void finishMultipart(DataOutputStream os) throws IOException {
// os.writeBytes(lineSpace);
os.flush();
os.writeBytes(delimiter + boundary + delimiter + lineSpace);
os.close();
}
private class ObjectUploadRunnable implements Runnable {
private final String _filePath;
private final String _url = domain + "upload.php";
public ObjectUploadRunnable(String filePath) {
_filePath = filePath;
}
#Override
public void run() {
try {
HttpURLConnection con = configureConnectionForMultipart(_url);
con.connect();
DataOutputStream os = new DataOutputStream(
con.getOutputStream());
File data = new File(_filePath);
addFilePart("data", data, os);
finishMultipart(os);
String response = getResponse(con);
Log.i("BoxUpload", response);
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I catch it on my server with the script upload.php:
...
$dir = "/uploads/";
$target_path = $dir.basename($_FILES['data']['name']);
if (move_uploaded_file($_FILES['data']['tmp_name'], $target_path)) {
echo "file uploaded";
} else {
echo print_r(error_get_last());
}
Everything seems to succeed, in that a file with the correct size gets uploaded to my server, in the desired directory. However, when I try to open the file, it seems to be damaged or corrupted in some way because it won't open in any application that I try. I'm uploading images=jpeg, videos=mp4, audio=mp4. These files are all working on the client before upload. Am I missing something to encode the files correctly in the POST request? I've never done file uploads before, so I'd appreciate some advice...
EDIT
In case this is relevant, I've noticed that the files which I've uploaded have grown by ~100kb. Maybe something's getting added to my binary data which is corrupting the file?
Figured out the problem here. That extra line that I commented out in addFilePart was actually necessary. I guess there needs to be two lines between the header info and the binary data in that part of the request. To be clear, it should look like:
private void addFilePart(String paramName, File data, DataOutputStream os)
throws IOException {
os.writeBytes(lineSpace + delimiter + boundary + lineSpace);
os.writeBytes("Content-Disposition: form-data; name=\"" + paramName
+ "\"; filename=\"" + data.getAbsolutePath() + "\"" + lineSpace);
os.writeBytes("Content-Type: application/octet \r\n");
os.writeBytes("Content-Transfer-Encoding: binary" + lineSpace);
os.writeBytes(lineSpace);
os.flush();
FileInputStream fis = new FileInputStream(data);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.writeBytes(lineSpace);
os.flush();
fis.close();
}
Everything works great now!

Categories