Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
Rishabh_Jain
Posts: 101
Registered: ‎07-11-2011
My Device: 8900
My Carrier: Airtel

Sending Extra Parameters while uploading Audio File On to server

Hi All,

 

I am Uploading audio file on to server which gets uploaded successfully.Now, i need to send extra 2 parameters, that i am not able to sen.Please help me to overcome this.Below is the code snippet for http connection:

 

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.io.http.HttpProtocolConstants;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.io.transport.ConnectionFactory;

public class PostFile {
	static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
	byte[] postBytes = null;
	String url = null;

	public PostFile(String url, String fileField, String fileName,
			String fileType, byte[] fileBytes) throws Exception {
		this.url = url;
		String boundary = getBoundaryString();
		String boundaryMessage = getBoundaryMessage(boundary, fileField,
				fileName, fileType);
		String endBoundary = "\r\n--" + boundary + "--\r\n";
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		bos.write(boundaryMessage.getBytes());
		bos.write(fileBytes);
		bos.write(endBoundary.getBytes());
		this.postBytes = bos.toByteArray();
		bos.close();
	}

	String getBoundaryString() {
		return BOUNDARY;
	}

	String getBoundaryMessage(String boundary, String fileField,
			String fileName, String fileType) {
		StringBuffer res = new StringBuffer("--").append(boundary).append(
				"\r\n");
		/*res.append("Content-Disposition: form-data; name=\"").append(fileField)
				.append("\"; filename=\"").append(fileName).append("\"\r\n");*/
		res.append("Content-Disposition: form-data; name=\"").append(fileField)
		.append("\"; filename=\"").append(fileName).append("\"\r\n")
		.append("Content-Type: ").append(fileType).append("\r\n\r\n");
		return res.toString();
	}

	public byte[] send(byte[] fileBytes) throws Exception {
		HttpConnection hc = null;
		InputStream is = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] res = null;
		ConnectionFactory connFact = new ConnectionFactory();

		ConnectionDescriptor connDesc;

		connDesc = connFact.getConnection(url);
		try {if (connDesc != null) {
			hc = (HttpConnection) connDesc
			.getConnection();
			//hc = (HttpConnection) Connector.open(url);
			hc.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + getBoundaryString());
			hc.setRequestMethod(HttpConnection.POST);
			hc.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET,
					"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
			hc.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH,
					Integer.toString(fileBytes.length));
			OutputStream dout = hc.openOutputStream();
			dout.write(postBytes);
			dout.close();
			int ch;
			final int iResponseCode = hc.getResponseCode();
			System.out.println("Response code is "+Integer.toString(iResponseCode));

			if (iResponseCode == HttpConnection.HTTP_OK) {
			/*is = hc.openInputStream();
			if (hc.getResponseCode() == HttpConnection.HTTP_OK) {*/
				/*synchronized (Application.getEventLock()) {
					Dialog.alert("Response Code : HTTP_OK!");
					
				}*/
				is = hc.openInputStream();
				System.out.println("Response Code : HTTP_OK!");
				while ((ch = is.read()) != -1) {
					bos.write(ch);
				}
				res = bos.toByteArray();
				
				String response = res.toString();
				System.out.println("response is after converting "+response);
				// System.out.println("res loaded..");
			}
		}} catch (IOException e) {
			e.printStackTrace();
			System.out.println("====IOException : " + e.getMessage());
			/*synchronized (Application.getEventLock()) {
				Dialog.alert("====IOException : " + e.getMessage());
			}*/
		} catch (Exception e1) {
			e1.printStackTrace();
			System.out.println("====Exception : " + e1.getMessage());
			/*synchronized (Application.getEventLock()) {
				Dialog.alert("====Exception : " + e1.getMessage());
			}*/
		} finally {
			try {
				if (bos != null)
					bos.close();

				if (is != null)
					is.close();

				if (hc != null)
					hc.close();
			} catch (Exception e2) {
				e2.printStackTrace();
				System.out.println("====Exception : "
						+ e2.getMessage());
				/*synchronized (Application.getEventLock()) {
					Dialog.alert("====Exception : "
							+ e2.getMessage());
				}*/
			}
		}
		return res;
	}
}

 Below is the code from where i am calling post file:

PostFile req = new PostFile(
					"http://202.162.188.101/fightback/upload_file.php", "file",
					fileName, "multipart/form-data; boundary=", fileBytes, _isMemoryAvailable);
			response = req.send(fileBytes);

 Now i need to send mentioned below parameters:

hc.setRequestProperty("fileMemStorage", "0");
			hc.setRequestProperty("userId", "Test123");

 Please help me through code, where should therse parametrs should get upload.So that it will be sent to server.

I have tried to debug throug wiredShark tool, to see what my http request get generated.But no success.

 

I have tried the same thing on my Android platform, that is running fine without any error.This means no problem at server side.Below is the code for my Android Platform:

@SuppressWarnings("deprecation")
       void doTask(){

              // codes to upload file on server
              Log.e(Constants.GOLBAL_TAG,"uploadFileOnServer");
              try{
                     HttpClient httpclient = new DefaultHttpClient();
                     //httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

                     /******** Server URL for Uploading ********/
                     //HttpPost httppost = new HttpPost("http://202.162.188.101/fightback/upload_file.php");

                     HttpPost httppost = new HttpPost(Constants.URL_BASE+Constants.UPLOAD_AUDIO_URL); 
                     MultipartEntity mpEntity = new MultipartEntity();
                     /********* The file to be uploaded is put here along with the path ********/

                     StringBody memoryAvailibity = new StringBody(isMemStorageAvailable+"");
                     if(filePath !=null){
                           File file = new File(filePath);
                           FileBody cbFile = new FileBody(file);
                           /********* This form parameter would be just like <input type="file" name="file" /> ********/
                           mpEntity.addPart("file", cbFile); 
                     }
                     mpEntity.addPart("fileMemStorage", memoryAvailibity); 

                     httppost.setEntity(mpEntity);
                     System.out.println("executing request[" + httppost.getRequestLine()+"]");
                     HttpResponse response = httpclient.execute(httppost);
                     HttpEntity resEntity = response.getEntity();

                     System.out.println(response.getStatusLine());
                     if (resEntity != null) {
                           System.out.println(EntityUtils.toString(resEntity));
                     }

                     httpclient.getConnectionManager().shutdown();
              }catch(Exception e){
                     e.printStackTrace();
              }

       }

 Please help me to overcome this.

Thanks in advance:smileyhappy:

Please use plain text.
Developer
peter_strange
Posts: 19,601
Registered: ‎07-14-2008
My Device: Not Specified

Re: Sending Extra Parameters while uploading Audio File On to server

"where should therse parametrs should get upload."

 

Add your two new lines:

 

hc.setRequestProperty("fileMemStorage", "0");
hc.setRequestProperty("userId", "Test123");

 

after this line:

 

hc.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH,
Integer.toString(fileBytes.length));

 

Please use plain text.