I need to upload videos from my android app to my website.
I use an async task and a method (included here below) to send the video, but I do not know how to set up the Perl scrip on my site that would interact with the app.
By now any test perl script (with any chmod combination) I use as a targetURL returns:
03-30 17:09:06.771: I/Server Response Code(21092): 403
03-30 17:09:06.771: I/Server Response Message(21092): Forbidden
I would greatly appreciate any general direction on how to make the Perl script and what permissions to give it.
I looked around the Internet for example, but there are few and in PHP, and I need it in Perl.
public String sendFileToServer(String filename, String targetUrl) {
String response = "error";
Log.e("Video filename", filename);
Log.e("url", targetUrl);
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
String pathToOurFile = filename;
String urlServer = targetUrl;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
SimpleDateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss");
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1024);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String connstr = null;
connstr = "Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ pathToOurFile + "\"" + lineEnd;
Log.i("Connstr", connstr);
outputStream.writeBytes(connstr);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.e("Video length", bytesAvailable + "");
try {
while (bytesRead > 0) {
try {
outputStream.write(buffer, 0, bufferSize);
} catch (OutOfMemoryError e) {
e.printStackTrace();
response = "outofmemoryerror";
return response;
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
} catch (Exception e) {
e.printStackTrace();
response = "error";
return response;
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("Server Response Code ", "" + serverResponseCode);
Log.i("Server Response Message", serverResponseMessage);
if (serverResponseCode == 200) {
response = "true";
}
String CDate = null;
Date serverTime = new Date(connection.getDate());
try {
CDate = df.format(serverTime);
} catch (Exception e) {
e.printStackTrace();
Log.e("Date Exception", e.getMessage() + " Parse Exception");
}
Log.i("Server Response Time", CDate + "");
filename = CDate
+ filename.substring(filename.lastIndexOf("."),
filename.length());
Log.i("File Name in Server : ", filename);
fileInputStream.close();
outputStream.flush();
outputStream.close();
outputStream = null;
} catch (Exception ex) {
// Exception handling
response = "error";
Log.e("Send file Exception", ex.getMessage() + "");
ex.printStackTrace();
}
return response;
}
Here is a example of server side code is written in Php. What it should be in Perl?
<?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";
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
?>
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 was able to upload the large files (Tested upto 1.2GB) to server using .setChunkedstreamingmode() using httpurlconnection. I learnt that we have to keep the url-connection live to send the large sized files. The code i used to upload the large sized files is,
public static String uploadFileToServer(String filename, String targetUrl) {
String response = "error";
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String pathToOurFile = filename;
String urlServer = targetUrl;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1024);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String token = "anyvalye";
outputStream.writeBytes("Content-Disposition: form-data; name=\"Token\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
outputStream.writeBytes("Content-Length: " + token.length() + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(token + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String taskId = "anyvalue";
outputStream.writeBytes("Content-Disposition: form-data; name=\"TaskID\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
outputStream.writeBytes("Content-Length: " + taskId.length() + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(taskId + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String connstr = null;
connstr = "Content-Disposition: form-data; name=\"UploadFile\";filename=\""
+ pathToOurFile + "\"" + lineEnd;
outputStream.writeBytes(connstr);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
System.out.println("Image length " + bytesAvailable + "");
try {
while (bytesRead > 0) {
try {
outputStream.write(buffer, 0, bufferSize);
} catch (OutOfMemoryError e) {
e.printStackTrace();
response = "outofmemoryerror";
return response;
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
} catch (Exception e) {
e.printStackTrace();
response = "error";
return response;
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
System.out.println("Server Response Code " + " " + serverResponseCode);
System.out.println("Server Response Message "+ serverResponseMessage);
if (serverResponseCode == 200) {
response = "true";
}else
{
response = "false";
}
fileInputStream.close();
outputStream.flush();
connection.getInputStream();
//for android InputStream is = connection.getInputStream();
java.io.InputStream is = connection.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while( ( ch = is.read() ) != -1 ){
b.append( (char)ch );
}
String responseString = b.toString();
System.out.println("response string is" + responseString); //Here is the actual output
outputStream.close();
outputStream = null;
} catch (Exception ex) {
// Exception handling
response = "error";
System.out.println("Send file Exception" + ex.getMessage() + "");
ex.printStackTrace();
}
return response;
}
Now during my upload process, if i pause the upload and resume, then it is starting from first byte instead of computing the chunks received by server. To overcome this problem, i coded as
// Initial download.
String lastModified = connection.getHeaderField("Last-Modified");
// Resume Upload.
connection.setRequestProperty("If-Range", lastModified);
But i am not able to resume the upload process. Can anyone please help me on this issue since i am newly learning this concepts. Thanks in Advance.
If the receiving server supports it, you can use the Content-Range header to identify a resuming upload. The Google-Drive API supports it. If you roll your own, I'd follow the pattern Google uses:
Begin upload and get a session identifier.
When upload is interrupted, wait until internet is available to resume.
When resuming upload, first inquire of the server how many bytes it has received. (*)
Resume upload with the next byte after the server's status.
(*) Note that when I rolled my own before, I added an encoded response from the server with the last KB of upload, just to verify it wasn't corrupted in transfer. However, I've never, in production, seen a case where a server had received corrupt data.
I am having trouble uploading a file using Java client to PHP appengine. I am able to upload file via browser as shown in this example. Also, the java client works when I deploy PHP appengine code on my local machine in development mode, but doesn't work on appengine. On appengine, $_FILES array is always empty. Here is the java code-
String uploadFile(String fileName){
Debug.inform(TAG, "file=" + fileName);
if (fileName.isEmpty()) {
return "file_empty";
}
String r = "";
String upload_url = "";
try {
Debug.inform(TAG, "origFile = " + fileName);
String charset = "UTF-8";
{ // Get upload url
String param = "Unique-Id";
String query = String.format("%s=%s", param, URLEncoder.encode(
SystemReader.readUniqueId(uniqueId), charset));
URL url = new URL(Configure.UPLOAD_URL + "?" + query);
final HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Accept-Charset", charset);
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Debug.inform(TAG, "HTTP Response: " + serverResponseMessage
+ ": " + serverResponseCode);
if (serverResponseCode == 200) {
String[] ret = getResult(conn);
upload_url = ret[0];
r = ret[1];
}
conn.disconnect();
}
if(!upload_url.equals("")) {
// Upload the file
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
FileInputStream fileInputStream = new FileInputStream(fileName);
URL url = new URL(upload_url);
final HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
//conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Accept-Charset", charset);
String shortFileName = fileName.substring(fileName
.lastIndexOf("/") + 1);
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
//conn.setFixedLengthStreamingMode(32944);
DataOutputStream dos = new DataOutputStream(
conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
+ shortFileName + "\"" + lineEnd +
"Content-Type: application/octet-stream" + lineEnd);
dos.writeBytes(lineEnd);
synchronized (fileWriteLock) {
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bytesRead);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
// Responses from the server (code and message)
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Debug.inform(TAG, "HTTP Response: " + serverResponseMessage
+ ": " + serverResponseCode);
conn.disconnect();
}
} catch (MalformedURLException ex) {
Debug.inform(TAG, "MalformedURLException");
r = "MalformedURLException";
} catch (IOException ioe) {
Debug.inform(TAG, "IOException");
r = "IOException";
}
}
First connection returns some results and upload URL formed from CloudStorageTools. This part is working fine. The next connection actually does the upload. I matched http headers sent by browser and the java code, they both look identical to me.
I have been stuck on this for long now. Thanks in advance.
I am trying to post 5 string values and an image to php server by using HTTPURLConnection. Getting Response code as 200 and Response message as OK but actual response after posting is not getting. Below is the code i am using:
public int sendRprtWithImageToServer(String getImagePath, String strEmailList){
String upLoadServerUri = "My URL";
String fileName = getImagePath;
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;
int serverResponseCode = 0;
File sourceFile = new File(getImagePath);
if (!sourceFile.isFile()) {
Log.e("Huzza", "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("stringkey1", stringvalue1);
conn.setRequestProperty("stringkey2", stringvalue2);
conn.setRequestProperty("stringkey3", stringvalue3);
conn.setRequestProperty("stringkey4", stringvalue4);
conn.setRequestProperty("stringkey5", stringvalue5);
conn.setRequestProperty("stringkey6", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"stringkey1\";filename=\""+ stringvalue1 + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"stringkey2\";filename=\""+ stringvalue2 + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"stringkey3\";filename=\""+ stringvalue3 + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"stringkey4\";filename=\""+ stringvalue4 + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"stringkey5\";filename=\""+ stringvalue5 + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"stringkey6\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
Log.i("Huzza", "Initial .available : " + bytesAvailable);
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);
InputStream is = conn.getInputStream();
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
Log.d("String response ", sb.toString());
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("Upload file to server", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
// close streams
Log.i("Upload file to server", fileName + " File is written");
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();
}
//this block will give the response of upload link
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.i("Huzza", "RES Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
}
return serverResponseCode; // like 200 (Ok)
}
Can anyone help me how to pass multiple parameters for HTTPURLConnection
I think you should use filebody to get file attach itself inside and 5 other string should be embedded inside multipart
public JSONObject file_upload1(String URL, String userid, String topic_id,
String topicname, String filelist, List<String> taglist,
String textComment, String textLink) {
JSONObject jObj = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
FileBody bin = null;
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filelist);
System.out.println("file name" + filelist.get(i));
try {
bin = new FileBody(file);
} catch (Exception e) {
e.printStackTrace();
}
reqEntity.addPart("post_data" + i, bin);
}
for (int i = 0; i < taglist.size(); i++) {
reqEntity.addPart("dtype" + i, new StringBody(taglist.get(i)));
}
reqEntity.addPart("tag", new StringBody("savetopicactivities"));
reqEntity.addPart("user_id", new StringBody(userid));
reqEntity.addPart("text", new StringBody(textComment));
reqEntity.addPart("count",
new StringBody(String.valueOf(taglist.size())));
reqEntity.addPart("topic_id", new StringBody(topic_id));
reqEntity.addPart("topic_name", new StringBody(topicname));
reqEntity.addPart("link", new StringBody(textLink));
httpPost.setEntity(reqEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
System.out.println("json " + json);
try {
jObj = new JSONObject(json);
} catch (Exception e) {
e.printStackTrace();
}
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// return JSON String
return jObj;
}
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.