Upload Large Image in Base64 to Server - java

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...

Related

Java make POST request to express js server and download PDF file

I have express js server as API. I need to send POST request to that server and my website needs to download PDF file to the client computer.
Here is my express server code:
const pdf = await generatePDF(data.originURL, data.url, data.pageOrientation); //pdf generation
// send pdf to client
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename=file.pdf',
'Content-Length': pdf.length
});
res.end(pdf);
In my website I have commandButton which call the action for POST request;
What I'm a doing wrong, I'm not getting any downloaded file in my website?
Method for making POST request:
public void makeRequest() {
HttpURLConnection connection = null;
try {
String imageExportServer = "url....";
URL url = new URL(imageExportServer);
connection = (HttpURLConnection)url.openConnection();
Stopwatch stopwatch = Stopwatch.createStarted();
try {
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
try (OutputStream stream = connection.getOutputStream()) {
JsonObject configJson = new JsonObject();
configJson.addProperty("originURL", "url");
configJson.addProperty("url", "url...");
configJson.addProperty("pageOrientation", "someText");
stream.write(Builder().create().toJson(configJson).getBytes());
}
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
//log.warn("Error response: ", responseCode);
}
String fileName = "";
String disposition = connection.getHeaderField("Content-Disposition");
String contentType = connection.getContentType();
int contentLength = connection.getContentLength();
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = connection.getInputStream();
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream("neki.pdf");
int bytesRead = -1;
byte[] buffer = new byte[contentLength];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
FileOutputStream fos = new FileOutputStream("neki.pdf");
fos.write(buffer);
fos.close();
System.out.println("File downloaded");
}
} catch (IOException e) {
//log.warn(e.getMessage(), e);
} finally {
//log.info("Exporting chart of type '%s' took %sms.", "tyoe", stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
} catch (IOException e) {
//log.warn(e.getMessage(), e);
} finally {
if (connection != null) {
try {
connection.disconnect();
} catch (Exception e) {
//log.warn(e.getMessage(), e);
}
}
}
}

HTTPUtils deprecated .. what do I do instead?

I need to download icons from the OpenWeatherMap website, build a URL, download the image, save it to local storage and also check to see if they already exist. HTTPUtils is underlined in red and when I looked it up, it's no longer being used. The Bitmap code was given to use by the professor.
#Override
protected String doInBackground(String... args) {
try {
URL url = new URL(TEMPS);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
//this is what talks to the xml on the website
xpp.setInput(inputStream, "UTF-8");
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (xpp.getName().equals("temperature")) {
curr = xpp.getAttributeValue(null, "value");
//tell android to call onProgressUpdate with 25 as parameter
publishProgress(25);
min = xpp.getAttributeValue(null, "min");
publishProgress(50);
max = xpp.getAttributeValue(null, "max");
publishProgress(75);
} else if (xpp.getName().equals("weather")) {
icon = xpp.getAttributeValue(null, "icon");
}
}
xpp.next();
}
//Start of JSON reading of UV factor:
//create the network connection:
URL UVurl = new URL(UV);
HttpURLConnection UVConnection = (HttpURLConnection) UVurl.openConnection();
inputStream = UVConnection.getInputStream();
//create a JSON object from the response
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
String result = sb.toString();
//now a JSON table:
JSONObject jObject = new JSONObject(result);
double aDouble = jObject.getDouble("value");
Log.i("UV is:", ""+ aDouble);
uv = aDouble;
//*****This is where I need help
Bitmap image = null;
URL imageUrl = new URL(IMAGE);
HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
image = BitmapFactory.decodeStream(connection.getInputStream());
}
image = HTTPUtils.getImage(IMAGE);
FileOutputStream outputStream = openFileOutput(icon + ".png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 80, outputStream);
outputStream.flush();
outputStream.close();
public boolean fileExistance(String weatherIcons){
File file = getBaseContext().getFileStreamPath(weatherIcons);
return file.exists();
Log.i("File name:", ""+ file);
}
FileInputStream fis = null;
try {
fis = openFileInput("C:/Users/kathy/AndroidStudioProjects/AndroidLabs/app/src/main/res/drawable");
} catch (FileNotFoundException e) {
Log.e("Download this file", e.getMessage());
}
Bitmap bm = BitmapFactory.decodeStream(fis);
publishProgress(100);
Thread.sleep(2000); //pause for 2000 milliseconds to watch the progress bar grow
} catch (Exception ex) {
}
return null;
}
While I don't really understand which package HTTPUtils comes from, I think relying on the standard classes from the JDK and Android SDK is the way to go.
try {
// Get an open Stream to the image bytes
final InputStream stream = new URL(IMAGE).openStream();
// Wrap the Stream in a buffered one for optimization purposes
// and decode it to a Bitmap
try (final InputStream bufferedInputStream = new BufferedInputStream(stream)) {
final Bitmap image = BitmapFactory.decodeStream(bufferedInputStream);
// Process the image
}
} catch (final IOException e) {
// Handle the Exception
}
You might want to extract an helper method, which simply returns the instantiated Bitmap variable.

How to get a file name from response header from HttpURLConnection?

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)

send files(images) from android device to webservice on the server written using REST [closed]

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

Failed to upload a file to web service

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

Categories