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.
Related
I need to send a request containing both data and a file to a server. When I just try to send the data it works, but if I also include the code for the file I get a FileNotFoundException, even though I can clearly see the number of bytes read from the file.
I have tried to set a bigger connection timeout, but nothing seems to be working.
This is the function which is supposed to send the data:
public String multipartRequest(String urlTo, Map<String, String> parmas, String filepath, String filefield) throws Exception {
HttpURLConnection 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;
Log.e("ceva", q[idx]);
try {
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
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);
connection.setRequestProperty("Accept", "application/json");
outputStream = new DataOutputStream(connection.getOutputStream());
if (!filepath.equals(""))
{
if(Build.VERSION.SDK_INT>22){
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
requestPermissions(permissions,1);
}
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
InputStream is = new BufferedInputStream(fileInputStream);
String fileMimeType = URLConnection.guessContentTypeFromStream(is);
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);
Log.e("baiti", Integer.toString(bytesRead));
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);
//fileInputStream.close();
}
// 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);
Log.e("something", "At least I got here");
if (200 != connection.getResponseCode()) {
//throw new Exception("Failed to upload code:" + connection.getInputStream() + " " + connection.getResponseMessage() + " " + connection.getContent());
}
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
inputStream.close();
outputStream.flush();
outputStream.close();
return result;
} catch (Exception e) {
Log.e("cam asta e", e.toString());
inputStream = connection.getInputStream();
return this.convertStreamToString(inputStream);
}
}
I expect to get a 200 code and a json as an answer, but instead I get 422 and the FileNotFoundException, even though the "At least I got here" line seems to be executed wherever I place it, so the code doesn't immediately get to the catch block.
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.
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 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";
}
I have an HttpURLConnection uploading a file, and my server then emails it. It works great. However, I don't want it in an Activity, I want it in the SMS receiver OnRecieve(), yet I can't seem to get it to work.
Please help? When I put the code into OnReceive(), it simply fails:(
Here's my code, it's quite simple:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try{
int serverResponseCode = 0;
final String upLoadServerUri = "http://MY_URL_EXAMPLE/upload_file_functions.php";
String fileName = "/mnt/sdcard/MyFile.dat";
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("/mnt/sdcard/MyFile.dat");
// 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("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";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);
// 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){
// it worked !
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
}catch (Exception e){
}
Bunch of F%$kn losers on here sometimes, I must say. I'll go ahead and answer my OWN question again:
You cannot do an httpURLrequest in BroadcastReceiver(). It must be done in a service:
public class UploadService extends IntentService
{
public UploadService()
{
super("UploadService");
}
#Override
protected void onHandleIntent(Intent intent)
{
public void postForm(String phn, String mssg)
{
try{
int serverResponseCode = 0;
final String upLoadServerUri = "http://MY_URL_EXAMPLE/upload_file_functions.php";
String fileName = "/mnt/sdcard/MyFile.dat";
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("/mnt/sdcard/MyFile.dat");
// 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("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";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);
// 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){
// it worked !
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
}catch (Exception e){
}
}
}
Called with:
context.startService(new Intent(context, UploadService.class));