您的位置:首页 > 其它

J2ME 文件上传 实例(FileConnector链接文件系统,非RMS)

2009-07-15 11:03 246 查看
客户端:

import java.io.InputStream;

import java.io.OutputStream;

import java.io.ByteArrayOutputStream;

import javax.microedition.io.*;

import javax.microedition.midlet.MIDlet;

import javax.microedition.midlet.MIDletStateChangeException;

import javax.microedition.io.file.*;

public class HttpConnect extends MIDlet {

public HttpConnect() {

// TODO Auto-generated constructor stub

}

protected void destroyApp(boolean arg0) throws MIDletStateChangeException {

// TODO Auto-generated method stub

}

protected void pauseApp() {

// TODO Auto-generated method stub

}

protected void startApp() throws MIDletStateChangeException{

String url = "http://192.168.0.114:8080/EngineService/sync";

try{

byte[] data = null;

if( System.getProperty("microedition.io.file.FileConnection.version" ) != null ){

try {

FileConnection fc = (FileConnection)Connector.open("file:///root1/test.png", Connector.READ_WRITE);

//fc.create();

InputStream in = fc.openInputStream();

fc.close();

ByteArrayOutputStream out = new ByteArrayOutputStream(4096);

byte[] tmp = new byte[4096];

int n;

while ((n = in.read(tmp)) != -1) {

out.write(tmp, 0, n);

out.flush();

}

in.close();

out.close();

data = out.toByteArray();

}catch (Exception e) {

e.printStackTrace();

}

}

HttpConnection sc = (HttpConnection)Connector.open( url, Connector.READ_WRITE, true );

sc.setRequestMethod( HttpConnection.POST );

sc.setRequestProperty("Content-Type", "application/octet-stream");

sc.setRequestProperty("Content-Length", String.valueOf(data.length));

OutputStream output = sc.openOutputStream();

output.write(data);

output.flush();

output.close();

}catch(Exception e){

System.out.println("Error:"+e);

}

}

}

服务器端:

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException

{

InputStream in = req.getInputStream();

byte[] tmp = new byte[4096];

int size=0;

File f = new File("c://",System.currentTimeMillis()+".png");

DataOutputStream o = new DataOutputStream(new FileOutputStream(f));

int len=0;

while((len = in.read(tmp))!= -1){

o.write(tmp,0,len);

o.flush();

size+=len;

}

o.close();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: