`
xixinfei
  • 浏览: 411030 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

HTTP Post multipart file upload in Java ME

    博客分类:
  • web
阅读更多

http://developer.nokia.com/Community/Wiki/HTTP_Post_multipart_file_upload_in_Java_ME

Here is a J2ME class to handle file uploads via HTTP POST Multipart Requests.

Source Code: HttpMultipartRequest class

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
 
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
 
public class HttpMultipartRequest
{
	static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
 
	byte[] postBytes = null;
	String url = null;
 
	public HttpMultipartRequest(String url, Hashtable params, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
	{
		this.url = url;
 
		String boundary = getBoundaryString();
 
		String boundaryMessage = getBoundaryMessage(boundary, params, 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, Hashtable params, String fileField, String fileName, String fileType)
	{
		StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
 
		Enumeration keys = params.keys();
 
		while(keys.hasMoreElements())
		{
			String key = (String)keys.nextElement();
			String value = (String)params.get(key);
 
			res.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n")    
				.append("\r\n").append(value).append("\r\n")
				.append("--").append(boundary).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() throws Exception
	{
		HttpConnection hc = null;
 
		InputStream is = null;
 
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
 
		byte[] res = null;
 
		try
		{
			hc = (HttpConnection) Connector.open(url);
 
			hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
 
			hc.setRequestMethod(HttpConnection.POST);
 
			OutputStream dout = hc.openOutputStream();
 
			dout.write(postBytes);
 
			dout.close();
 
			int ch;
 
			is = hc.openInputStream();
 
			while ((ch = is.read()) != -1)
			{
				bos.write(ch);
			}
			res = bos.toByteArray();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(bos != null)
					bos.close();
 
				if(is != null)
					is.close();
 
				if(hc != null)
					hc.close();
			}
			catch(Exception e2)
			{
				e2.printStackTrace();
			}
		}
		return res;
	}
}

Sample usage

Here's a code snippet to upload a file via HttpMultipartRequest class:

byte[] fileBytes = getFileBytes(); //retrieve file bytes with your own code
 
Hashtable params = new Hashtable();
params.put("custom_param", "param_value");
params.put("custom_param2", "param_value2");
 
HttpMultipartRequest req = new HttpMultipartRequest(
	"http://www.server.com/uploadScript.php",
	params,
	"upload_field", "original_filename.png", "image/png", fileBytes
);
 
byte[] response = req.send();

Sample server code (PHP)

This is a sample PHP script that handles the upload. It doesn't actually save the uploaded file, but only displays some infos about the upload size and parameters.

<?php
 
$filesize = filesize($_FILES['upload_field']['tmp_name']);
 
echo "The uploaded file size is " . $filesize . " bytes\n";
 
foreach($_POST as $key => $value)
{
	echo "Parameter name: " . $key . ", value: " . $value . "\n";
}
 
?>

 

 

 

Comments

this piece of code works great, but i am having a little problem the HttpConnection its not Setting the Content-Lenght and the transfer its being made with transfer-encodign: chunked

i dont know if tha later is giving problems but the thing about the content-lenght its giving some problems with a server with mod_sec that its forbiding REQUEST without Content-Lenght header so im getting a 403 its there any way to set the content-Lenght? setRequestParameter() i think is not working thanks in adavance

 

Maximum file size that can be uploaded from mobile

 

I tried the same example. I am able to upload file which are less than 150 bytes. If I upload the file more than that size I get the following error. Please help me in this

java.io.IOException: error 104 during TCP read

 

       at com.sun.midp.io.j2me.socket.Protocol.nonBufferedRead(Protocol.java:299)
       at com.sun.midp.io.BufferedConnectionAdapter.readBytes(BufferedConnectionAdapter.java:99)
       at com.sun.midp.io.BaseInputStream.read(ConnectionBaseAdapter.java:582)
       at com.sun.midp.io.BaseInputStream.read(ConnectionBaseAdapter.java:511)
       at java.io.DataInputStream.read(+7)
       at com.sun.midp.io.j2me.http.Protocol.readLine(+4)
       at com.sun.midp.io.j2me.http.Protocol.readResponseMessage(+17)
       at com.sun.midp.io.j2me.http.Protocol.finishRequestGetResponseHeader(+39)
       at com.sun.midp.io.j2me.http.Protocol.sendRequest(+50)
       at com.sun.midp.io.j2me.http.Protocol.sendRequest(+6)
       at com.sun.midp.io.j2me.http.Protocol.closeOutputStream(+4)
       at com.sun.midp.io.BaseOutputStream.close(ConnectionBaseAdapter.java:737)
       at hello.HttpMultipartRequest.send(HttpMultipartRequest.java:91)
       at hello.PostMIDlet.run(PostMIDlet.java:104)

 

 

Thanks in advance Smith,

 

Nokia 6300 and J2ME problems

 

I made MIDDLET which is capable of working to Semens CX75. (Very old!) My MIDDLET create photo and send it to site by HTTP. But "Nokia 6300" reject my MIDDLET.

Help me!

(1) I find sample: HTTP Post multipart file upload with J2ME HTTP Post multipart file upload with J2ME But it is not an example. It is a hint. It cannot be compiled!

Show to us an example which is compiled by WTK2.5.2 and carried out by Nokia S40 devices.

(2) Show to us an prescription which should compile WTK2.5.2 MIDDLETs examples for Nokia S40 devices. (In particular "CameraDemo" and HttpConnection-samples.)

 

Away123 - Upload Just only 1 KB

Can i use this class for upload file bigger than 1 KB ? Please help me..

分享到:
评论

相关推荐

    minio-multipart-upload:使用预先签名的URL的分段上传对象

    $ curl --location --request POST ' 127.0.0.1:8006/multipart/init ' \ --header ' Content-Type: application/json ' \ --data-raw ' { "filename": "b.jpg", "partCount": 2, "contentType": "image/jpeg" } ...

    multipart-post:向nethttp添加了多部分POST功能

    Multipart :: Post 向Net::HTTP添加了流式多部分表单发布功能。 除POST外,还支持其他方法。 功能/问题 似乎可以正常工作。 一个很好的功能。 封装文件/二进制部分和名称/值参数部分的发布,类似于大多数浏览器的...

    上传文件fileupload+解决enctype= multipart/form-data无法传递其他参数

    解决上传文件enctype= multipart/form-data 时无法传递其他参数的问题,以及项目全局编码问题。用的插件是commons io + commons fileupload

    java上传文件实例

    &lt;form action="index.jsp?flag=1" method="post" enctype="multipart/form-data" name="form1"&gt; &lt;input type="file" name="file"&gt; &lt;input type="hidden" name="file"&gt; 上传"&gt; &lt;/form&gt;&lt;/td&gt; if(null != request....

    express-multipart-file-parser:Express解析器,允许使用多部分数据上传文件,与Google Cloud功能兼容

    const fileParser = require ( 'express-multipart-file-parser' ) . . . app . use ( fileParser ) . . . app . post ( '/file' , ( req , res ) =&gt; { const { fieldname , originalname , encoding , mime...

    Apache Commons fileUpload实现文件上传

    out.print("the upload file name is" + item.getName()); out.print(" "); } } } else { out.print("the enctype must be multipart/form-data"); } %&gt; &lt;html&gt; &lt;head&gt; &lt;meta ...

    Java邮件开发Fundamentals of the JavaMail API

    POP stands for Post Office Protocol. Currently in version 3, also known as POP3, RFC 1939 defines this protocol. POP is the mechanism most people on the Internet use to get their mail. It defines ...

    AspUpload.zip

    &lt;FORM METHOD="POST" ENCTYPE="multipart/form-data" ACTION="UploadScript1.asp"&gt; &lt;INPUT TYPE=FILE SIZE= 60NAME="FILE1"&gt; &lt;INPUT TYPE=FILE SIZE= 60NAME="FILE2"&gt; &lt;INPUT TYPE=FILE SIZE= 60NAME="FILE3"&gt; ...

    HBuilder+HTML5 Plus+MUI实现拍照或者相册选择图片上传

    Uploader上传使用HTTP的POST方式提交数据,数据格式符合Multipart/form-data规范,即rfc1867(Form-based File Upload in HTML)协议。 --------------------- 作者:A_山水子农 来源:CSDN 原文:...

    fileupload文件上传

    文件上传: 一,导包 1,commons-fileupload-1.2.2.jar 2,导入commons-io-2.0.1.jar 二,客户端 1,表单的method属性必须是post 2,必须包含name属性,如:...3,表单中加入属性:enctype="multipart/form-data

    c# http post get

    client.UploadFile("http://hiup.baidu.com/zhangsan/upload", @"file1=D:\1.mp3");//上传文件 client.UploadFile("http://hiup.baidu.com/zhangsan/upload", "folder=myfolder&size=4003550",@"file1=D:\1.mp3");...

    JavaScript File分段上传

    form method="POST" name="form" action="/mupload/upload/" enctype="multipart/form-data"&gt; &lt;input type='hidden' name='csrfmiddlewaretoken' value='' /&gt; &lt;input id='file' type='file' name='file'...

    无组件ASP文件上传源代码

    &lt;form name="form" method="post" action="saveannouce_upfile.asp" enctype="multipart/form-data" &gt; 文件 &lt;input type="file" name="file1" size=10&gt; 上传"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; -------------------...

    多文件上传

    &lt;form enctype="multipart/form-data" method="post" action="doUpload.jsp"&gt; 上传文件: &lt;td&gt;&lt;input type="file" name="nfile" /&gt; 添加" onclick="addFile()"&gt; 上传"&gt; =================...

    MVC上传资料

    &lt;!DOCTYPE ...&lt;form action="/Home/Upload" enctype="multipart/form-data" method="post"&gt; &lt;input type="file" name="file1" /&gt; 文件上传" /&gt; &lt;/html&gt;

    struts2文件上传下载

    struts2文件上传与下载, &lt;s:form name="Myform" action="/fileManage/upload" method="post" enctype="multipart/form-data" theme="simple" &gt; &lt;s:fielderror&gt;&lt;/s:fielderror&gt; &lt;s:file name="image" label=...

    fileupload

    &lt;form method="post" action="upload.jsp" name="pw" enctype="multipart/form-data"&gt; 文件一 &lt;input type="file" name="file1"&gt; 文件二 &lt;input type="file" name="file2"&gt; ...

    JspSmartUpload上传文件到文件夹重名问题解决方法

    &lt;form action="upd2.jsp" method="post" enctype="multipart/form-data" name="form1"&gt; &lt;input type="file" name="file1"&gt; 上传" &gt; 接受上传文件:okUpload.jsp 接受图片改变名称保存到指定目录并在...

    微信企业号项目

    DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while((bytes = in.read(bufferOut))!=-1) { out.write(bufferOut,0,bytes); } ...

    Upload-to-serverless-offline:使用multer上载无服务器离线环境的示例

    这是使用multipart / fom-data上传二进制文件的示例无服务器离线HTTP代理$ npm i && npm start从命令行将文件上传到端点Httpie( ) $ http -vf POST localhost:3000/dev/serverless-http/upload file@"./image1....

Global site tag (gtag.js) - Google Analytics