I am currently uploading file in android. Now I want to send some data lets say and ID with that fileupload. So I will deal with this ID on the server side. Here is how I am uploading file. This code works perfectly fine.
Here is the code
public int uploadFile(String sourceFileUri, final String imageName) {
//Toast.makeText(getApplicationContext(), imageName, Toast.LENGTH_LONG).show();
String upLoadServerUri = "http://www.example.com/android/fileupload.php";
String fileName = sourceFileUri;
//Toast.makeText(getApplicationContext(), sourceFileUri, Toast.LENGTH_LONG).show();
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()) {
Log.e("uploadFile", "Source File Does not exist");
return 0;
}
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
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);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
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();
Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
//tv.setText("File Upload Completed.");
if(fileData(globalUID, imageName)) {
Toast.makeText(Camera.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
Toast.makeText(Camera.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
Toast.makeText(Camera.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
You can write query string onto output stream.
OutputStream os = conn.getOutputStream();
os.write( yourQueryString.getBytes( withSpecificCharset ) );
And in the server php script you can read query parameters as usual.
$param1 = $_POST[ "param1" ];
You can refer to BalusC's community wiki answer on How to use java.net.URLConnection to fire and handle HTTP requests?. It discussed with examples on HTTP Post with file upload and query parameters.
Related
I am uploading files to my server with a Java class in my Android APP.
I am using a simple php Skript to check a password.
If I give the wrong password, the file is not saved on the server and I should get 403, but I get OK 200 from the server.
Here is the Java Class
class httpUploadFile {
private int serverResponseCode = 0;
int uploadFile(String upLoadServerUri, String uploadFilePath, String uploadFileName,String pfad) {
String sourceFileUri=uploadFilePath + "" + uploadFileName;
HttpURLConnection conn;
DataOutputStream dos;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + uploadFileName);
return 0;
}
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
String fulluri=getUrl(upLoadServerUri,pfad);
URL url = new URL(fulluri);
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", sourceFileUri);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";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();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
Log.e("Upload file Exception", "Exception : "
+ e.getMessage(), e);
}
return serverResponseCode;
}
private String getUrl(String BASE_URL,String pfad) {
String token = getToken();
String key = getKey(token);
return String.format("%s?token=%s&key=%s&pfad=%s&", BASE_URL, token, key,pfad);
}
private String getKey(String token) {
return md5(String.format("%s+%s", "wrongpassword", token));
}
private String getToken() {
return md5(UUID.randomUUID().toString());
}
private static String md5(String s) {
MessageDigest m = null;
try {
m = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
assert m != null;
m.update(s.getBytes(), 0, s.length());
return new BigInteger(1, m.digest()).toString(16);
}
}
and here is the PHP
<?php
$shared_secret = "password";
$key = $_GET['key'];
$token = $_GET['token'];
$pfad = $_GET['pfad'];
if ($key != hash("md5", "{$shared_secret}+{$token}")) {
header('HTTP/1.0 403 Forbidden');
die('403 Forbidden: You are not allowed to access this file.');
}
$file_path = "/home/www/data/".$pfad."/";
$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";
}
?>
HTTP 200 means transmission is OK on the HTTP level,that is to say, request was technically OK and server was able to respond properly.
200 doesn't judge whether your business logic is true or false, so even password is wrong, only if http communication between server and client is normal, 200 will be returned.
Generally we respond with HTTP 5xx if technical or unrecoverable problems happened on the server. Or HTTP 4xx if the incoming request had issues (e.g. wrong parameters)
Your backend server should do above judge.
I'm using this class to upload image to php server from my android app.
But I want to send some parameters such as custom file name, user who uploaded the file etc.
Is there any way to send some parameters while uploading the file?
Example: name=newimage&uploadedby=username
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);
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);
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);
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn
.getResponseMessage();
if (serverResponseCode == 200) {
//Toast.makeText(ctx, "File Upload Complete.",
// Toast.LENGTH_SHORT).show();
}
fileInputStream.close();
dos.flush();
dos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return "Executed";
}
}
Is there any way to do this with header request, like this:
conn.setRequestProperty("parameters","name=filename&uploadedby=username");
yes it is possible
I am not a java developer but in PHP you can receive such data in 2 ways: as parameter in the URL which will be available in PHP in the $_GET array
Example, change your URL to:
String upLoadServerUri = "http://website.com/abc.php?filename=blabla&anotherparam=1234";
then in PHP: echo $_GET['filename']. $_GET is also available if you are POSTing your request.
or/and you can do this in your POST. Your POST request can contain as many extra params as you need. Here is an example how you could do this.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to write a function that will upload any filev to my server. I've searched all over the internet but have found nothing useful without using any external libraries. Any suggestions?
try this
public int uploadFile(String sourceFileUri, String destUri)
{
String fileName = sourceFileUri;
Log.e("YOUR_TAG", "uploading file: " + sourceFileUri);
HttpURLConnection conn;
DataOutputStream dos;
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() && !sourceFile.exists())
{
Log.e(YOUR_TAG, "Source File not exist :" + imagepath);
return 0;
} else {
try
{
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(destUri);
// 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("file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
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);
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i(YOUR_TAG, "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200)
{
Log.d(YOUR_TAG, "success: " + sourceFileUri);
//do your stuff here
}
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e(YOUR_TAG, "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
Log.e(YOUR_TAG, "Exception : " + e.getMessage(), e);
}
return serverResponseCode;
}
}
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
.addFileToUpload(path, "f_url") //Adding file
.addHeader("Authorization", "Bearer " + token) //Adding token
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
As i took the code from the one of stack overflow answers.
Send .txt file, document file to the server in android
Modifying the following code, I'm trying to POST audio/video file to online php server. Everything works fine the file is uploading correctly and saving in database but the problem is I am also sending parameters with the file so that i can recognize which user is sending recordings, (user_id and candidate_id and file_type) but in database their values are null/0.
Please someone tell me whats wrong with my code why its not working for params. As i checked my php side server with POSTMAN all the values are saving correctly with file.
try {
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(Config.URL_UPLOAD);
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("uploadedfile", fileName);
dos = new DataOutputStream(conn.getOutputStream());
//here am adding the params
param.put("user_id", Constants.user_id);
param.put("candidate_id", "candiidateid1");
param.put("file_type", Constants.file_type);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(dos, "UTF-8"));
writer.write(getPostDataString(param));
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";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);
dialog.dismiss();
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
DataInputStream inStream = null;
if (serverResponseCode == 200) {
try {
Log.e("isStream = ", "" + inStream);
inStream = new DataInputStream(conn.getInputStream());
String str;
Log.e("isStream = ", "" + inStream);
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
Log.e("isStream = ", "" + inStream);
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
Log.e("Upload file to server ",
"Exception : " + e.getMessage(), e);
}
Refer the below URL it ha clear answer to pass the parameters
Sending files using POST with HttpURLConnection
i need to send a data to server using multipart i have successfully sending image to server using HttpURLConnection Multipart image is loading successfully but i am sending id also but id is not sending to server. so can you help me where is error .i
public String uploadData() {
String fileName = mRealProfilePicPath;
// Log.e("mrealpath",fileName);
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(mRealProfilePicPath);
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
// URL url = new URL("http://stank.cwsdev3.biz/text.php/");
// URL url = new
// URL(AppUtills.BASE_URL+"user/update_profile?&dump=1");
URL url = new URL(AppUtills.BASE_URL + "user/update_profile?");
// 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("profilepic", fileName);
conn.setRequestProperty("first_name", firstName);
// conn.setRequestProperty("dump","1");
// conn.setRequestProperty("id",
// AppPreference.getUserId(con,AppUtills.USERID));
dos = new DataOutputStream(conn.getOutputStream());
String param1 = AppPreference.getUserId(con, AppUtills.USERID);
dos.writeBytes("Content-Disposition: form-data; name=\"id\""
+ lineEnd);
dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
dos.writeBytes("Content-Length: " + param1.length() + lineEnd); // unable to upload this
dos.writeBytes(lineEnd);
dos.writeBytes(param1 + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"profilepic\";filename=\""
+ fileName + "\"" + lineEnd); // image uploading
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();
Log.e("uploadFile", "HTTP Response is : " + serverResponseMessage
+ ": " + serverResponseCode);
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
int responseCode = conn.getResponseCode();
Log.e("TAG, POST Response Code :: ", "" + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.i("TAG", response.toString());
return response.toString();
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
}
return "no";
}