J2ME手机本地文件上传服务器
J2ME手机本地存储文件的上传,核心代码如下:
package com.mopietek;import javax.microedition.midlet.MIDlet;import javax.microedition.midlet.MIDletStateChangeException;import com.sun.lwuit.Display;public class MainMIDlet extends MIDlet{private MainPanel panel = null;protected void destroyApp(boolean unconditional)throws MIDletStateChangeException {// TODO Auto-generated method stub}protected void pauseApp() {// TODO Auto-generated method stub}protected void startApp() throws MIDletStateChangeException {Display.init(this);panel = new MainPanel(this);}public void exit(){try{destroyApp(false);}catch(MIDletStateChangeException e){e.printStackTrace();}this.notifyDestroyed();}}
package com.mopietek;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration;import javax.microedition.io.Connector;import javax.microedition.io.HttpConnection;import javax.microedition.io.file.FileConnection;import javax.microedition.io.file.FileSystemRegistry;import com.sun.lwuit.Command;import com.sun.lwuit.Component;import com.sun.lwuit.Container;import com.sun.lwuit.Dialog;import com.sun.lwuit.Form;import com.sun.lwuit.Label;import com.sun.lwuit.List;import com.sun.lwuit.TextArea;import com.sun.lwuit.events.ActionEvent;import com.sun.lwuit.events.ActionListener;import com.sun.lwuit.layouts.BorderLayout;import com.sun.lwuit.list.ListCellRenderer;import com.sun.lwuit.plaf.Border;public class MainPanel implements ActionListener{private final String UP_DIR = "..";private final String SEPS_STR = "/";private final int SEPS_CHAR = '/';private final String ROOT = "/";private final String RES_PREFIX = "file://";private final int BLOCK_SIZE = 256;private final String TEXT_EXT[] = {".TXT",".H",".HPP",".C",".CPPC",".INC"};private final String IMAGE_EXT[] = {".JPG",".JPEG",".PNG",".GIF"};private final String WEB_EXT[] = {".HTM",".HTML",".XML",".CSS"};private final String CHARACTER_CODE = "UTF-8";private MainMIDlet let = null;//主界面private Form listForm = null;//内容列表private List contentList = null;//显示文件用窗体private Form textForm = null;private TextArea text = null;private Form imageForm = null;private Command cmdExit = null;private Command cmdView = null; //浏览目录/文件private Command cmdDone = null; //退出浏览文件内容private Command cmdUpload = null; //上传文件private IconHelper helper = null;private String currentDir = null;public MainPanel(MainMIDlet mainMIDlet) {let = mainMIDlet;currentDir = ROOT;helper = new IconHelper();listForm = new Form();listForm.setLayout(new BorderLayout());cmdExit = new Command("退出");cmdView = new Command("浏览");cmdDone = new Command("返回");listForm.addCommand(cmdView);listForm.addCommand(cmdExit);listForm.addCommandListener(this);new BrowseThread(currentDir,true).start();}public void actionPerformed(ActionEvent evt) {Command c = evt.getCommand();if(c == cmdExit){let.exit();}else if(c == cmdView){if(contentList.size() == 0){new BrowseThread(ROOT,true).start();}else{final String url = ((MyContainer) contentList.getSelectedItem()).name.getText();if(url.endsWith(SEPS_STR) == true){new BrowseThread(currentDir + url,true).start();}else if(url.endsWith(UP_DIR) == true){backward();}else{new BrowseThread(currentDir + url,false).start();}}}else if(c == cmdDone){new BrowseThread(currentDir,true).start();}}private void backward(){int pos = currentDir.lastIndexOf(SEPS_CHAR, currentDir.length() -2);if(pos != -1){currentDir = currentDir.substring(0, pos +1);}else{currentDir = ROOT;}new BrowseThread(currentDir,true).start();}class MyContainer extends Container{private Label name;public MyContainer(String source){name = new Label(source);name.getStyle().setBgTransparency(0);addComponent(name);}}class MyRenderer implements ListCellRenderer{private Label focus;public MyRenderer(){focus = new Label();Border b = Border.createLineBorder(1, 0xff0000);focus.getStyle().setBorder(b);}public Component getListCellRendererComponent(List list, Object value,int index, boolean selected) {return (MyContainer) value;}public Component getListFocusComponent(List list) {return focus;}}class BrowseThread extends Thread{private String url = null;private boolean isDirectory = false;public BrowseThread(final String _url,final boolean _isDirectory){url = _url;isDirectory = _isDirectory;}public void run(){if(isDirectory){showDir(url);}else {showFile(url);}}public void showDir(final String dir){Enumeration em = null;FileConnection fc = null;currentDir = dir;listForm.removeAll();contentList = new List();contentList.setListCellRenderer(new MyRenderer());listForm.addComponent(BorderLayout.CENTER,contentList);try{if(dir.equals(ROOT) == true){//枚举根目录列表em = FileSystemRegistry.listRoots();}else{//非根目录fc = (FileConnection) Connector.open(RES_PREFIX + dir);em = fc.list();MyContainer up = new MyContainer(UP_DIR);up.name.setIcon(helper.getIconByExt("/"));contentList.addItem(up);}while(em.hasMoreElements()){String fileName = (String) em.nextElement();if(fileName.endsWith(SEPS_STR)){//如果为目录MyContainer c = new MyContainer(fileName);c.name.setIcon(helper.getIconByExt("/"));contentList.addItem(c);System.out.println("filName------>"+fileName);}else{//非目录(文件)MyContainer c = new MyContainer(fileName);c.name.setIcon(helper.getIconByExt(extractExt(fileName)));contentList.addItem(c);}}listForm.revalidate();contentList.setSelectedIndex(0,true);if(fc != null){fc.close();}}catch(Exception ex){ex.printStackTrace();}listForm.show();}//文件上传public void showFile(final String fileName){String url = "http://dev.mopietek.net:8080/waptest_1.0/httpup";String tempFileName = fileName.toUpperCase();byte[] data = null;try{FileConnection fc = (FileConnection) Connector.open(RES_PREFIX + fileName,Connector.READ);if(!fc.exists()){Dialog.show("Exception", "未找到文件", "ok","cancel");}if(isEndWithIn(tempFileName,IMAGE_EXT) == true){InputStream is = fc.openInputStream();ByteArrayOutputStream out = new ByteArrayOutputStream(4096);byte[] tmp = new byte[4096];int n;while((n = is.read(tmp)) != -1){out.write(tmp, 0, n);out.flush();}is.close();out.close();data = out.toByteArray(); }if(fc != null){fc.close();}}catch(Exception ex){ex.printStackTrace();}try {HttpConnection sc = (HttpConnection) Connector.open(url, Connector.READ, 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 (IOException e) {e.printStackTrace();}}//private String getRelativeName(final String fileName){//int pos = fileName.lastIndexOf(SEPS_CHAR);//if(pos == -1){//return ("");//}//return (fileName.substring(pos + 1, fileName.length()));//}private boolean isEndWithIn(final String fileName,final String[] extArray){for(int i=0;i<extArray.length;i++){if(fileName.endsWith(extArray[i]) == true){return true;}}return false;}//获取扩展名(不包括'.'符号)private String extractExt(final String fileName){int pos = fileName.lastIndexOf('.');return (fileName.substring(pos + 1, fileName.length()).toLowerCase());}}}
package com.mopietek;import java.io.IOException;import java.util.Hashtable;import com.sun.lwuit.Image;public class IconHelper {//图标资源private Image imgFolder;private Image unknownImage;private Image textImage;//Audioprivate Image audioImage;//Pictureprivate Image picImage;private Image jpgImage;//Videoprivate Image sgpImage;private Image aviImage;private Image wmvImage;private Image mpgImage;//Webprivate Image zipImage;private Image htmlImage;private Image xmlImage;//Sourceprivate Image cImage;private Image cppImage;private Image headerImage;//图标管理容器private Hashtable iconTable;public IconHelper(){iconTable = new Hashtable();try{//载入图标资源imgFolder = Image.createImage("/filetype/folder.png");unknownImage = Image.createImage("/filetype/unknown.png");textImage = Image.createImage("/filetype/text.png");//AudioaudioImage = Image.createImage("/filetype/audio.png");//PicturepicImage = Image.createImage("/filetype/pic.png");jpgImage = Image.createImage("/filetype/jpg.png");//VideosgpImage = Image.createImage("/filetype/3gp.png");aviImage = Image.createImage("/filetype/avi.png");wmvImage = Image.createImage("/filetype/wmv.png");mpgImage = Image.createImage("/filetype/mpg.png");//WebzipImage = Image.createImage("/filetype/zip.png");htmlImage = Image.createImage("/filetype/html.png");xmlImage = Image.createImage("/filetype/xml.png");//SourcecImage = Image.createImage("/filetype/c.png");cppImage = Image.createImage("/filetype/cpp.png");headerImage = Image.createImage("/filetype/header.png");}catch(IOException e){//图标资源imgFolder = null; unknownImage = null; textImage = null; //Audio audioImage = null; //Picture picImage = null; jpgImage = null; //Video sgpImage = null; aviImage = null; wmvImage = null; mpgImage = null; //Web zipImage = null; htmlImage = null; xmlImage = null; //Source cImage = null; cppImage = null; headerImage = null; e.printStackTrace(); }initTable();}private void initTable() { //Key为扩展名(不包括'.'符号),值为content typeiconTable.put("/", imgFolder);iconTable.put("", unknownImage);iconTable.put("txt", textImage);//SourceiconTable.put("c", cImage);iconTable.put("cpp", cppImage);iconTable.put("h", headerImage);//WebiconTable.put("html", htmlImage);iconTable.put("htm", htmlImage);iconTable.put("xml", xmlImage);iconTable.put("zip", zipImage);iconTable.put("jar", zipImage);//audioiconTable.put("mp3", audioImage);iconTable.put("wma", audioImage);iconTable.put("mid", audioImage);iconTable.put("wav", audioImage);//PictureiconTable.put("gif", picImage);iconTable.put("png", picImage);iconTable.put("jpg", jpgImage);iconTable.put("jepg", jpgImage);//VideoiconTable.put("3gp", sgpImage);iconTable.put("avi", aviImage);iconTable.put("wmv", wmvImage);iconTable.put("mpeg", mpgImage);iconTable.put("mpg", mpgImage);iconTable.put("mp4", mpgImage);} //按照扩展名(不包括'.'符号) 获取文件的图标对象public Image getIconByExt(final String extension) {Image temp = (Image) iconTable.get(extension);//是否为空,则使用默认图标替代return ((temp == null) ? unknownImage : temp);}}