Android - HTTPURLConnection fails while posting multiple inputs - java

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;
}

Related

Problems using HttpUrlconnection to do login and upload an image

I've made an API which has an authorization part and a body part. The body part is for users to upload an image. For the basic auth part, it just need the username and the password. For the uploading part, it needs two parameters and an jpeg image file. I just got from some resources for uploading file but not combining the login part, so I modify it myself, but I don't know what's wrong in my code, it doesn't work. The following is my code:
public String multipartRequest(String urlTo, Map<String, String> parmas, String filepath, String filefield, String fileMimeType) throws CustomException {
HttpsURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String[] q = filepath.split("/");
int idx = q.length - 1;
try {
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlTo);
connection = (HttpsURLConnection) url.openConnection();
///// certification
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory newFactory = sc.getSocketFactory();
connection.setSSLSocketFactory(newFactory);
connection.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
String a = username + ":" + password;
byte[] data = a.getBytes();
String info = "Basic " + Base64.encodeToString(data, Base64.DEFAULT);
connection.setRequestProperty("Authorization", info);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
// Upload POST Data
Iterator<String> keys = parmas.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = parmas.get(key);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(value);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
return result;
} catch (Exception e) {
throw new CustomException("error e");
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
I don't know why it doesn't work.
Does anyone know how to use httpurlconnection to do both login and uploading files? In my code, I add both the following lines, is this a problem? I mean use "Content-Type" for multiple times(Login and Uploading files):
For Login part:
connection.setRequestProperty("Content-Type", "text/plain");
For uploading file part:
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
But I call them at the same time(same function), is this a problem?

Uploading file to server NOT WORKING

My code is below.
After uploading (time is varying for different file sizes) I got 200 Ok and response
public class CloudFileUploader extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
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;
try {
FileInputStream fileInputStream = new FileInputStream(mFile);
URL url = new URL(CloudConstants.getFileUploadBaseUrl());
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary + ";key=fileToUpload");
conn.setRequestProperty("Accept", "application/json");
String contentLength=Long.toString(mFile.length());
// conn.setRequestProperty("Content-Length",contentLength );
AppSharedPreference mPref = new AppSharedPreference(mContext);
String token = mPref.getStringPrefValue(PreferenceConstants.USER_TOKEN);
conn.setRequestProperty("token", token);
conn.setRequestProperty("groupId", "" + mMessage.getReceiverId());
conn.setRequestProperty("message", "" + mMessage.getMessageBody());
conn.setRequestProperty("messageType", "" + mMessage.getMessageType());
conn.setRequestProperty("senderName", "" + mMessage.getSenderName());
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + mFile.getName() + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
Log.i(TAG, "Initial .available : " + bytesAvailable);
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();
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException | FileNotFoundException | ProtocolException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (serverResponseCode == 200) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException ex) {
ex.printStackTrace();
if (onFileUploadListener != null) {
onFileUploadListener.onUploadFailed(mMessage, new AppError(ErrorHandler.ERROR_FROM_SERVER, ErrorHandler.ErrorMessage.ERROR_FROM_SERVER));
}
}
return sb.toString();
} else {
return "Could not upload";
}
}
}
I put conn.setRequestProperty("Content-Length",contentLength ); but it will throw java.net.ProtocolException.
I tested differnt code but the issue is still there.
Below given is my php server script.
$status['apiId'] = _GROUP_FILE_UPLOAD_API;
$user_id = $this->user['user_id'];
$target_dir = ROOTDIR_PATH . DS . "data" . DS . "GroupFileUploads" . DS;
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$fileUpload = NULL;
if ($this->headers->get('groupId')) {
$fileUpload['groupId'] = $groupId = $this->headers->get('groupId')->getFieldValue();
}
if ($this->headers->get('messageType')) {
$fileUpload['messageType'] = $messageType = $this->headers->get('messageType')->getFieldValue();
} if ($this->headers->get('message')) {
$fileUpload['message'] = $message = $this->headers->get('message')->getFieldValue();
}
if ($this->headers->get('senderName')) {
$fileUpload['senderName'] = $senderName = $this->headers->get('senderName')->getFieldValue();
}
The code is not working. It is not saving anything to the folder I given.
But It is working from Postman and AdvancedRestClient
When I put die() then i Got
Array( [myFile] => Array ( [name] => 1495018448FaceApp_1494992050886.jpg [type] => [tmp_name] => /tmp/phpH2kH47 [error] => 0 [size] => 917953 ))
The [type] => should be image/jpg but it is empty

Android: Why am I unable to upload an image to a web server?

I'm using HttpUrlConnection to upload an image to a web server. When I run the app and attempt to upload an image I get a Http response 200 as well as receive the filename and the imageid of the supposed image that has been uploaded, but when i check the server the image was not uploaded. The filename and the id are now part of the list but when I attempt to retrieve the image it returns null.
public String uploadFile(String apiPath, String filePath, String type)
{
String path = "";
String result = "";
switch (type)
{
case "M":
path = "Merchant/" + apiPath;
break;
case "C":
path = "Customer/" + apiPath;
break;
}
Log.i(ApiSecurityManager.class.getSimpleName(), m_token);
String href = "http://tysomapi.fr3dom.net/" + path + "?token=" + m_token;
Log.i(ApiSecurityManager.class.getSimpleName(), href);
try
{
String myIp = getIp();
URL url = new URL(href);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", "java");
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary = " + boundary);
conn.setRequestProperty("X-Forwarded-For", myIp);
conn.setDoOutput(true);
File file = new File(filePath);
DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
ds.writeBytes(twoHyphens + boundary + LINE_FEED);
ds.writeBytes("Content-Disposition: form-data; name=\"image\"; filename=\"" + file.getName() + "\"" + LINE_FEED);
ds.writeBytes("ContentType: image/peg" + LINE_FEED);
ds.writeBytes(twoHyphens + boundary + LINE_FEED);
FileInputStream fStream = new FileInputStream(file);
int bytesAvailable = fStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
ds.write(buffer, 0, bufferSize);
bytesAvailable = fStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fStream.read(buffer, 0, bufferSize);
}
ds.writeBytes(LINE_FEED);
ds.writeBytes(twoHyphens + boundary + twoHyphens + LINE_FEED);
fStream.close();
ds.flush();
ds.close();
Log.i(getClass().getSimpleName(), "Response Code: " + conn.getResponseCode());
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
while ((output = br.readLine()) != null)
{
result = result + output;
}
conn.disconnect();
}
catch (
MalformedURLException e
)
{
e.printStackTrace();
}
catch (
IOException e
)
{
e.printStackTrace();
}
return result;
}
I was able to fix the problem by using PrintWriter and OutputStream instead of DataOutputStream to pass the headers and the image.

Unable to Send parameter In 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";
}

Uploading large files from android app to server using Perl

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;
}
?>

Categories

Resources