Please see below my service code:
if (Request.Content.IsMimeMultipartContent())
{
try
{
Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(new MultipartMemoryStreamProvider()).ContinueWith((task) =>
{
MultipartMemoryStreamProvider provider = task.Result;
foreach (HttpContent content in provider.Contents)
{
Stream stream = content.ReadAsStreamAsync().Result;
if (stream == null)
lst.Add(new ResponseMsg { status = "Stream empty" });
else
{
Image image = Image.FromStream(stream);
var testName = content.Headers.ContentDisposition.Name;
String fileName = content.Headers.ContentDisposition.FileName;
String fullPath = Path.Combine(path, "sample_" + DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString() + ".jpg");
image.Save(fullPath);
lst.Add(new ResponseMsg { status = "success" });
}
}
});
lst.Add(new ResponseMsg { status = "Request content empty" });
}
catch (Exception e)
{
lst.Add(new ResponseMsg { status = e.Message });
}
}
else
{
lst.Add(new ResponseMsg { status = "This request is not properly formatted" }); ;
}
And, this is my android code:
try {
InputStream result = null;
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(
"/storage/sdcard0/DCIM/Camera/1417504088698.jpg");
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL("URL");
// 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("Cache-Control", "no-cache");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
//conn.setRequestProperty("uploaded_file", "1417504088698.jpg");
//conn.setRequestProperty("Image", text);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"\";filename=\""
+ "1417504088698.jpg" + "\"" + 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);
}
dos.write(buffer);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
result = (InputStream) conn.getContent();
if (result != null) {
Reader reader = new InputStreamReader(result);
Gson gson = new Gson();
if (reader != null) {
rMsg = gson.fromJson(reader, ResponseMsg[].class);
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
While executing I am getting statusCode : OK, with message : "Request content empty". The file is not saved in the server. How can I fix this issue. Please help.
Related
I got a FileNotFoundException error.
Code:
File getpath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
String dir= getpath.getAbsolutePath();
Log.e("filename of dir",dir);
//"/storage/emulated/0/Movies/"
try {
FileInputStream fstrm = new FileInputStream(dir+filename);
VideoFileUploadNew hfu = new VideoFileUploadNew( ServerURL.VIDEO_UPLOAD, filename);
upflag = hfu.Send_Now(fstrm);
Log.e("filename of v up",filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
public class VideoFileUploadNew implements Runnable {
URL connectURL;
String responseString;
String Title;
String fileName;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
public VideoFileUploadNew(String urlString, String file){
try{
connectURL = new URL(urlString);
fileName = file;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
public Boolean Send_Now(FileInputStream fStream){
fileInputStream = fStream;
return Sending();
}
Boolean Sending(){
System.out.println("file Name is :"+fileName);
String iFileName = fileName;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="fSnd";
try
{
Log.e(Tag,"Starting Http File Sending to URL");
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes("Content-Disposition: form-data; name=\"vfile\";filename=\"" + iFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize =9024;
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, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0,bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.close();
dos.flush();
Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
String s=b.toString();
Log.i("Response",s);
dos.close();
if(String.valueOf(conn.getResponseCode()).equals("200"))
{
return true;
}else{
return false;
}
}
catch (MalformedURLException ex)
{
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
return false;
}
#Override
public void run() {
}
}
Your question is still pretty vague, but one of the reasons this happens is- when you're fetching the relative URI of the File, but need the Absolute URI for the upload.
You can check out different FileUtil classes like this https://github.com/z0rawarr/AndroidUtilCode/blob/master/utilcode/src/main/java/com/blankj/utilcode/utils/FileUtils.java
Get the absolute path from the URI and use that to upload.
Also, do not forget to use the Debugger, and apply a breakpoint on uploadFile() to debug the URIs.
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() ); //HERE IT STOPS WORKING WITHOUT AN ERROR
I'm using ADT and no Emulator (directly connected to my Smartphone). The file upload works, if I upload the file directly over an HTML request through my browser. Any ideas how i could solve this?
Use My Method To Upload
private void doFileUpload() {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;// 1 MB
String responseFromServer = "";
String urlString = Constant.URL + "upload_fil.php";
try {
// ------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(
selectedPath));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
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=\"uploaded_file\";filename=\""
+ imageName + "\"" + lineEnd);
Log.i(TAG, "Uploading starts");
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) {
Log.i(TAG, "Uploading");
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);
// close streams
Log.e("Debug", "File is written");
Log.i(TAG, "Uploading ends");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
ioe.printStackTrace();
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
onUploadComplete();
try {
final JSONObject jsonObject = new JSONObject(str);
if (jsonObject.getBoolean("status")) {
handler.post(new Runnable() {
public void run() {
try {
Toast.makeText(getApplicationContext(),
jsonObject.getString("message"),
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} else {
handler.post(new Runnable() {
#Override
public void run() {
try {
Toast.makeText(getApplicationContext(),
jsonObject.getString("message"),
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
inStream.close();
} catch (IOException ioex) {
ioex.printStackTrace();
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
I am sending a file from sd card by using the following code.
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/111";
File f = new File(existingFileName);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://192.178.1.7/Geo/Prodect(filename)";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(f);
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
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=\"uploadedfile\";filename=\"" + existingFileName + "\"" + 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)
Log.v("info",".size."+bytesRead);
for(int n1=0;n1<bytesRead;n1++)
{
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);
// close streams
Log.v("info","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.v("info", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.v("info", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.v("info","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex)
{
Log.v("info", "error: " + ioex.getMessage(), ioex);
}
It works fine but,the file contains 20 lines it saved in the sever with 22 lines.
My actual file looks like as follows.
android app info
app name
app time
when i will send the flle to server from sd card the file look like as follows
1)**mnt/sdcard/111**
android app info
app name
app time
2)**
1 and 2 lines are added.
How i can send a file without those two lines .
If any one know the solution please help me .
Thanks in advance..
public static StringBuffer post(String url,InputStream in) throws IOException {
InputStream bufferInputStream = null;
InputStreamReader responseInputStream = null;
HttpURLConnection conn = null;
OutputStream requestOutputStream = null;
StringBuffer responseString = new StringBuffer();
int bufferSize = 8192;
byte[] byteBuffer = new byte[bufferSize];
int postDataSize = 0;
try {
if (in != null) {
bufferInputStream = new BufferedInputStream(in);
}
if (bufferInputStream != null) {
postDataSize = bufferInputStream.available();
}
//send request
conn = getConnecttion(url);
if (postDataSize > 0) {
requestOutputStream = conn.getOutputStream();
int position = 0;
while ((position = bufferInputStream.read(byteBuffer)) > -1) {
requestOutputStream.write(byteBuffer, 0, position);
}
requestOutputStream.flush();
requestOutputStream.close();
requestOutputStream = null;
byteBuffer = null;
}
// get response
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
responseInputStream = new InputStreamReader(conn.getInputStream(),"UTF-8");
char[] charBuffer = new char[bufferSize];
int _postion = 0;
while ((_postion=responseInputStream.read(charBuffer)) > -1) {
responseString.append(charBuffer,0,_postion);
}
responseInputStream.close();
responseInputStream = null;
charBuffer = null;
}else{
throw new IOException("Respsone code:"+responseCode);
}
} catch (Exception e) {
e.printStackTrace();
throw new IOException(e.getMessage());
} finally {
byteBuffer = null;
if (responseInputStream != null) {
responseInputStream.close();
responseInputStream = null;
}
if (conn != null) {
conn.disconnect();
conn = null;
}
if (requestOutputStream != null) {
requestOutputStream.close();
requestOutputStream = null;
}
if (bufferInputStream != null) {
bufferInputStream.close();
bufferInputStream = null;
}
}
return responseString;
}
Please reference to above simple code,
send file like this:post("http://youurl.com",new FileInputStream(" you file path"))
Try commenting the following
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes(lineEnd);
I want to upload a file to server using http.
try {
URL url = new URL(dst);
File file = new File(src);
urlconnection = url.openConnection();
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
if (urlconnection instanceof HttpURLConnection) {
try {
((HttpURLConnection)urlconnection).setRequestMethod("PUT");
((HttpURLConnection)urlconnection).setRequestProperty("Content-type", "text/html");
((HttpURLConnection)urlconnection).connect();
} catch (ProtocolException e) {
e.printStackTrace();
}
}
BufferedOutputStream bos = new BufferedOutputStream(urlconnection
.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
int i;
// read byte by byte until end of stream
while ((i = bis.read()) >0) {
bos.write(i);
}
System.out.println(((HttpURLConnection)urlconnection).getResponseMessage());
}
catch(Exception e1)
{
e1.printStackTrace();
}
try {
InputStream inputStream;
int responseCode=((HttpURLConnection)urlconnection).getResponseCode();
if ((responseCode>= 200) &&(responseCode<=202) ) {
inputStream = ((HttpURLConnection)urlconnection).getInputStream();
int j;
while ((j = inputStream.read()) >0) {
System.out.println(j);
}
} else {
inputStream = ((HttpURLConnection)urlconnection).getErrorStream();
}
((HttpURLConnection)urlconnection).disconnect();
} catch (IOException e) {
e.printStackTrace();
}
on System.out.println(((HttpURLConnection)urlconnection).getResponseMessage()); line writes "Not Implemented" I couldn't find why
upload file to php server
public void uploadFile(String sourceFileUri) {
Log.e("upload Started", "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy");
String fileName = sourceFileUri;
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 not exist :" + sdcard + ""
+ "log.txt");
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
// conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", device_id + ".txt");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ device_id + ".txt" + "\"" + 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) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(STB.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
DataInputStream inStream = new DataInputStream(
conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
// 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) {
e.printStackTrace();
}
} // End else block
}
I want to copy all the video files on my server & save it in the web contents folder of a web service , so that it can be visible to all later on !
How should i proceeed ?
Basically you need two sides. The first one is on Android. You have to send (Do it in an ASyncTask e.x.) the data to your webservice. Here I made a little method for you, which sends a file and some additional POST values to an URL:
private boolean handleFile(String filePath, String mimeType) {
HttpURLConnection connection = null;
DataOutputStream outStream = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://your.domain.com/webservice.php";
try {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(filePath));
} catch(FileNotFoundException e) { }
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outStream = new DataOutputStream(connection.getOutputStream());
// Some POST values
outStream.writeBytes(addParam("additional_param", "some value");
outStream.writeBytes(addParam("additional_param 2", "some other value");
// The file with the name "uploadedfile"
outStream.writeBytes(twoHyphens + boundary + lineEnd);
outStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filePath +"\"" + lineEnd + "Content-Type: " + mimeType + lineEnd + "Content-Transfer-Encoding: binary" + lineEnd);
outStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outStream.writeBytes(lineEnd);
outStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
outStream.flush();
outStream.close();
} catch (MalformedURLException e) {
Log.e("APP", "MalformedURLException while sending\n" + e.getMessage());
} catch (IOException e) {
Log.e("APP", "IOException while sending\n" + e.getMessage());
}
// This part checks the response of the server. If its "UPLOAD OK" the method returns true
try {
inStream = new DataInputStream( connection.getInputStream() );
String str;
while (( str = inStream.readLine()) != null) {
if(str=="UPLOAD OK") {
return true;
} else {
return false;
}
}
inStream.close();
} catch (IOException e){
Log.e("APP", "IOException while sending\n" + e.getMessage());
}
return false;
}
Now, we have got the other side: http://your.domain.com/webservice.php
Your server. It needs some logic, for example in PHP, to handle the sent POST request.
Something like this would work:
<?php
$target_path = "videos/";
$target_path = $target_path.'somename.3gp';
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
exit("UPLOAD OK");
} else {
exit("UPLOAD NOT OK");
}
?>