I have a web service that get a audio and do some operation on it and finally returns a string ,this web service have a web page like this
<form name="form1" method="post" action="Default.aspx" id="form1" enctype="multipart/form-data">
<input type="file" name="FileUpload3" id="FileUpload3" style="width:325px;" />
<input type="submit" name="Button6" value="Upload File" id="Button6" />
<span id="Label1"></span>
</form>
when file choose for uploadfile3 and press upload file a same page should be reload and then show the string in span lable, I want to connect this web service by android so I tried below code to connect and upload file, the server response 200 code but no file uploads to server and no string shows, it seems that server press upload file without choosing file, what can I do? help please.
public void upLoad2Server() throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://11.12.13.174/file_transfer_sample/ClientWebSite/Default.aspx");
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/test.wav");
ContentBody cbFile = new FileBody(file, "audio/wav");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("FileUpload3", cbFile);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
Log.i("status", String.valueOf(response.getStatusLine()));
}
Check this code to upload file from Android to Web Server
public class UploadFileToServer extends AsyncTask<Object, String, Object>
{
URL connectURL;
String params;
String responseString;
String fileName;
byte[] dataToServer;
FileInputStream fileInputStream;
private int serverResponseCode;
private String serverResponseMessage;
private static final String TAG = "Uploader";
public void setUrlAndFile(String urlString, File fileName)
{
Log.d(TAG,"StartUploader");
try
{
fileInputStream = new FileInputStream(fileName);
connectURL = new URL(urlString);
}
catch(Exception e)
{
e.getStackTrace();
publishProgress(e.toString());
}
this.fileName = fileName.getAbsolutePath()+".txt";
}
synchronized void doUpload()
{
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
Log.d(TAG,"lv1");
try
{
Log.d(TAG,"doUpload");
publishProgress("Uploading...");
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
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(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition:form-data; name=\"Uploaded\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.d(TAG,"LvA");
Log.d(TAG,twoHyphens + boundary + lineEnd + ";Content-Disposition:form-data; name=\"Uploaded\";filename=\"" + fileName + "\"" + lineEnd);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer,0, bufferSize);
Log.d(TAG,"LvB");
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);
fileInputStream.close();
dos.flush();
InputStream is = conn.getInputStream();
int ch;
Log.d(TAG,"LvC");
StringBuffer buff = new StringBuffer();
while((ch=is.read()) != -1)
{
buff.append((char)ch);
}
// publishProgress(buff.toString());
dos.close();
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
// Log.d(TAG,"Buffer "+buff.toString());
Log.d(TAG,"Server Response "+serverResponseMessage);
}
catch(Exception e)
{
e.getStackTrace();
publishProgress(e.toString());
}
}
#Override
protected Object doInBackground(Object... arg0)
{
Log.d(TAG,"lv1a");
doUpload();
Log.d(TAG,"Uploading Completed! Path: "+connectURL);
return null;
}
protected void onProgressUpdate(String... progress)
{
//this.info.setText(progress[0]);
Log.d("Progress", progress[0]);
}
}
Thanks
Check this code.It's upload a file to .NET httphandler server. It uses SSL self-signed security, but it's an example how to use methods, and multipart entity. It works for me.
public static void main(String[] args) throws IOException {
try {
File f = new File(
"c:\\eula.1028.txt");
System.out.println("LENGTH " + f.length());
PostMethod method = new PostMethod("/Handler");
FilePart filePart = new FilePart("file",f);
filePart.setContentType("application/pdf");
Part[] parts = {filePart};
MultipartRequestEntity request = new
MultipartRequestEntity(parts, method.getParams());
method.setRequestEntity(request);
Protocol easyhttps = new Protocol("https",
new EasySSLProtocolSocketFactory(), 2000);
org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
client.getHostConfiguration().setHost("localhost", 2000, easyhttps);
client.executeMethod(method);
String s = method.getResponseBodyAsString();
System.out.println(s);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Related
I want to upload mp3 file from Android app to my asp.net server, I am using this class on client side
import android.util.Log;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpFileUpload implements Runnable{
URL connectURL;
String responseString;
String Title;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
public HttpFileUpload(String urlString, String vTitle, String vDesc){
try{
connectURL = new URL(urlString);
Title= vTitle;
Description = vDesc;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
public void Send_Now(FileInputStream fStream){
fileInputStream = fStream;
Sending();
}
void Sending(){
String iFileName = "temp.mp3";
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(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Title);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Description);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
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, 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();
}
catch (MalformedURLException ex)
{
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
Then I using the above class like that
public void uploadFile(){
try {
File appDir = getContext().getExternalFilesDirs(null)[0];
File file = new File(appDir.getAbsolutePath() + "/Audios");
if (!file.exists()) {
file.mkdirs();
}
fileName = appDir.getAbsolutePath() + "/Audios/temp.mp3";
FileInputStream fstrm = new FileInputStream(fileName);
// Set your server page url (and the file title/description)
HttpFileUpload hfu = new HttpFileUpload("http://www.example.com/Fileup.aspx", "my file title","my file description");
hfu.Send_Now(fstrm);
} catch (FileNotFoundException e) {
// Error: File not found
}
}
And this is the server side asp.net code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Fileup : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
string vTitle = "";
string vDesc = "";
string FilePath = Server.MapPath("~/files/cur_file.mp3");
if (!string.IsNullOrEmpty(Request.Form["title"]))
{
vTitle = Request.Form["title"];
}
if (!string.IsNullOrEmpty(Request.Form["description"]))
{
vDesc = Request.Form["description"];
}
HttpFileCollection MyFileCollection = Request.Files;
if (MyFileCollection.Count > 0)
{
// Save the File
MyFileCollection[0].SaveAs(FilePath);
}
}
}
Notes:
I added INTERNET & EXTERNAL STORAGE permission to my client app
The client side reaches to this line and return code 500 Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode())); and then throw exception in the next line InputStream is = conn.getInputStream();
Then I can't find the mp3 file in "files" folder on my Server
The mp3 file just 16 kb
What is the problem?
I solved it, There was no permission to write files for the folder "files", Thanks
I take a picture using the android.hardware.Camera API. I then convert it to a Bitmap of half the actual size, compress it to a JPEG of quality 80, convert it to Base64 and send it to the server as follows.
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.NO_WRAP);
String json_response = "";
try {
URL url = new URL("https://example.com/api_endpoint");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write("?reg=" + regCode);
writer.write("&img=" + encoded);
writer.flush();
writer.close();
os.close();
Log.d("Auth", conn.getResponseCode() + "");
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
String text = "";
while ((text = br.readLine()) != null) {
json_response += text;
}
conn.disconnect();
} catch (IOException e) {
Log.d(getClass().getName(), "" + e.getMessage());
}
This works as expected. Now, If I don't resize the image and keep the quality 100%, how should I go about to avoid an OutOfMemoryError? My application requires the image to be in the full resolution and best quality possible.
My questions are:
Is the way I am uploading the correct way?
How to send Image is best quality without OutOfMemoryError i.e. how to optimize RAM usage in this process?
Here is my image/file uploader class:
public class ImageUploader extends AsyncTask<String, String, String> {
File imageFile = null;
String fileName = null;
public ImageUploader(File imageFile, String fileName){
this.imageFile = imageFile;
this.fileName = fileName;
}
#Override
protected String doInBackground(String... params) {
String url_str = params[0];
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="fSnd";
try {
URL url = new URL(url_str);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("POST");
c.setDoInput(true);
c.setDoOutput(true);
c.setRequestProperty("Connection", "Keep-Alive");
c.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
c.connect();
DataOutputStream dos = new DataOutputStream(c.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + this.fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
FileInputStream fin = new FileInputStream(imageFile);
int bytesAvailable = fin.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[ ] buffer = new byte[bufferSize];
int bytesRead = fin.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fin.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fin.read(buffer, 0,bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fin.close();
dos.flush();
dos.close();
StringBuilder response = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(c.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
return response.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
}
return null;
}
}
Usage:
new ImageUploader(pictureFile, "sample.jpg"){
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
}.execute("http://example/upload.php");
PHP:
<?php
$file = explode('.', $_FILES['file']['name']);
$ext = $file[count($file) - 1];
$name = substr($_FILES['file']['name'], 0, (strlen($ext) + 1) * -1);
$location = 'images/';
$cntr = 1;
$tmp_name = $name;
if(move_uploaded_file($_FILES['file']['tmp_name'], $location.$tmp_name.'.'.$ext)){
echo "Image was uploaded.";
}else{
echo "Image was not uploaded.";
}
?>
If you have the control over the API endpoint. Then try to implement the POST request to accept multi-part uploading from client side.
On client-side, have something like this to upload the image to API (with Okhttp client)
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", "logo-square.png",
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
I think problem not with downloading to server. If I understand correctly, you getting image from camera and sending it. Note, that if you using simple request intent, that returns in onActivityResult() - Bitmap Image - this may be point of OutOfMemoryException...
Solution it's use another form on Intent() method, (that can get storage path in his parameters) for getting photo from camera, that doesn't return Bitmap image. But save photo to path, which you specified. And now you can do anything with photo in path, without OutOfMemoryException...
Sample starting correct Intent:
File destination = new File(Environment.getExternalStorageDirectory(),
"image.jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(destination));
startActivityForResult(intent, CAMERA_PICTURE);
Let me know, this helps...
I have Client Server program, Client make a connection to server with its URL and server Reads a file and writes to outputstream and client will get that file and save it in a directory. Problem is I am not getting the filename I am sending in response from Server. Here is my Client Server Code.
Client,
private void receiveFile() throws IOException {
String url11="http://localhost:8080/TestServer/TestServer";
// creates a HTTP connection
URL url = new URL(UPLOAD_URL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
int responseCode = httpConn.getResponseCode();
String ff=httpConn.getHeaderField("filename");
System.out.println("FHeader :"+ff);
File saveFile = new File(SAVE_DIR + ff);
StringBuilder builder = new StringBuilder();
builder.append(httpConn.getResponseCode())
.append(" ")
.append(httpConn.getResponseMessage())
.append("\n");
if (responseCode == HttpURLConnection.HTTP_OK) {
// reads server's response
System.out.println(builder);
InputStream inputStream = httpConn.getInputStream();
// opens an output stream for writing file
FileOutputStream outputStream = new FileOutputStream(saveFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Receiving data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data received.");
outputStream.close();
inputStream.close();
} else {
System.out.println("Server returned non-OK code: " + responseCode);
}
}
Server ,
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int BUFF_SIZE = 1024;
byte[] buffer = new byte[BUFF_SIZE];
String filePath = "E:\\Docs\\Next stop is Kurki.MP3";
File fileMp3 = new File(filePath);
if(fileMp3.exists()){
System.out.println("FOUND : ");
} else {
System.out.println("FNF");
}
String fNmae=fileMp3.getName();
FileInputStream fis = new FileInputStream(fileMp3);
response.setContentType("audio/mpeg");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fNmae + "\"");
response.addHeader("fName", fNmae);
response.setContentLength((int) fileMp3.length());
OutputStream os = response.getOutputStream();
try {
int byteRead = 0;
while ((byteRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, byteRead);
}
os.flush();
} catch (Exception excp) {
// downloadComplete = "-1";
excp.printStackTrace();
} finally {
os.close();
fis.close();
}
}
I feel everything is correct in Server side , Can any one help me to sort this. It would be great help . thank you.
Try this in server:
File file = new File("E:\\Docs\\Next stop is Kurki.MP3");
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition",
"attachment; filename="Next stop is Kurki.MP3");
return response.build();
When client is android :
wv = webView;
wv.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir("/YouPath", fileName);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
Attention here in client String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to send images from android device to my web application running on server with tomcat. please help me in writing small code for sending image to a REST web service running on Web server. Please provide me the sample code if possible. I am stuck with what method to use. Any help would be greatly appreciated. thanks in advance.
Edit: The answer for this question is as follows
while(it.hasNext()){
File file = new File((new StringBuilder()).append(Environment.getExternalStorageDirectory()).append(File.separator).append("jcms").append(File.separator).append("Customer_").append( customer.getId()).toString());
File[] listOfFiles = file.listFiles();
for(int i=0;i<listOfFiles.length;i++){
JSONObject message = new JSONObject();
File fil=listOfFiles[i];
FileInputStream imageInFile = new FileInputStream(fil);
byte imageData[] = new byte[(int)fil.length()];
imageInFile.read(imageData);
String imageDataString = encodeImage(imageData);
URL url=new URL(ClearCustomersContract.CLEAR_SERVER_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(imageDataString);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
while (in.readLine() != null) {
}
in.close();
}
}
And The REST Webservice on server side is like
#Override
#POST
#Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_OCTET_STREAM})
#Path("/getData")
public Response getAllTheSyncData(InputStream incomingData) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
System.out.println("Error Parsing: - ");
}
return Response.status(200).entity("Success").build();
}
and this is how we convert the string back to image.
byte[] imageByteArray = decodeImage(jsonObj.get("imageData").toString());
imageOutFile = new FileOutputStream(
"C:/Users/SUNILKUMAR/Desktop/result.jpg");
// Write a image byte array into file system
imageOutFile.write(imageByteArray);
imageOutFile.close();
Check the link . it gives complete example of how to upload file to server.
or check below code -
public class HttpFileUpload implements Runnable{
URL connectURL;
String responseString;
String Title;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
HttpFileUpload(String urlString, String vTitle, String vDesc){
try{
connectURL = new URL(urlString);
Title= vTitle;
Description = vDesc;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
void Send_Now(FileInputStream fStream){
fileInputStream = fStream;
Sending();
}
void Sending(){
String iFileName = "ovicam_temp_vid.mp4";
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(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Title);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Description);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
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, 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();
}
catch (MalformedURLException ex)
{
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
public void UploadFile(){
try {
// Set your file path here
FileInputStream fstrm = new FileInputStream(Environment.getExternalStorageDirectory().toString()+"/DCIM/file.mp4");
// Set your server page url (and the file title/description)
HttpFileUpload hfu = new HttpFileUpload("http://www.myurl.com/fileup.aspx", "my file title","my file description");
hfu.Send_Now(fstrm);
} catch (FileNotFoundException e) {
// Error: File not found
}
}
You can use below code to upload image with REST webservice
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(
"YOUR WEB SERVICE URL");
entity = getMultipleEntityUpload();
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost,
httpContext);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(
is));
while ((line = rd.readLine()) != null) {
total.append(line);
}
String result =total.toString();
} catch (Exception e) {
// TODO: handle exception
}
private MultipartEntity getMultipleEntityUpload() {
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//imagePic is bitmap of your image
imagePic.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] arrByteImage = stream.toByteArray();
try {
entity.addPart(WS_Key_Constant.KEY_IMAGE, new ByteArrayBody(
arrByteImage, ".jpg"));
} catch (Exception e) {
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return entity;
}
I'm working on a project that needs to upload image using Multipart.
Here is my code:
public void doUploadGIF(File image) {
try {
long start = System.currentTimeMillis();
HttpPost httppost = new HttpPost(
"myurl");
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("gif", new FileBody(image));
httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
long end = System.currentTimeMillis();
System.out.println("Time for uploading:"
+ String.valueOf(end - start));
} catch (Exception e) {
Log.e("Upload", "Error while uploading");
}
}
private class PhotoUploadResponseHandler implements ResponseHandler<Object> {
#Override
public Object handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
HttpEntity r_entity = response.getEntity();
String responseString = EntityUtils.toString(r_entity);
Log.d("UPLOAD", responseString);
return null;
}
}
Now in client side (Android) I let the user know the process of uploading ( percent ).
How can I do that?
Thanks for your attention !
in my case I used the file size in KB and set the limit of the progressbar with the file size in KB. and for updating the progressbar I used :
int bufferLength = 1024;
File file = new File(ImgURI);
mFileLen = file.length();
int maxBufferSize = 1*1024*1024;
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
for (int i = 0; i < bufferSize; i +=bufferLength) {
progress = i/1024;
progressBar1.setMax(kbfilesize);
publishProgress(progress);
}