您的位置:首页 > 其它

j2ee上传文件自制组件

2008-12-15 19:29 357 查看
[/b]
[/b]
上传文件组件说明[/b]
[/b]
[/b]
上传组件设计思想:

这里的自制上传组件用的是HttpServletRequest 方法上传的
,
首先我们通过 HttpServletRequest 方法获取到 request所获取

到的http传过来的流,然后将流读入到一个临时文件内.然后我们用一个方法来解析这个文件.因为通过http传过来的流生成的临时

文件的结构如下:

-----------------------------7d33a816d302b6

Content-Disposition: form-data; name="userfile1"; filename="E:/s"

Content-Type: application/octet-stream

a

bb

XXX

ccc

-----------------------------7d33a816d302b6

Content-Disposition: form-data; name="text1"

foo

-----------------------------7d33a816d302b6

Content-Disposition: form-data; name="password1"

bar

-----------------------------7d33a816d302b6--

然后我们只需要解析临时文件,就能提取出上传文件内容和上传控件内容.在解析上传文件时,一并将文件类型,文件大小获取到.并

且我们可以根据这样的方法限制上传文件大小和类型

.
我们将获取到的上传控件名和上传控件值存入到hashtable(K,V)中.

将获取到的上传文件流的信息(文件名,文件大小,文件类型…)存入到Vector中.然后将存入到Vector相应的索引和控件名存入到

Hashtable中.

这样我们就可以将上传流和控件对应的值获取到.然后在重载getParameter()方法,并且 一并重载request的其他方法.这样 一个

完整的上传文件空间就做成了.

本上传组件使用方法

方法摘要

方法名
参数类型返回值说明
SetSize(int number)
Int类型Void设置上传文件的大小,若不设置,则只能上传10M文件,若

设为-1,则上传文件大小不控制

setSuffix(String suffix)
String 类型Void设置上传文件类型若不设置,则可以上传所有文件.[例如: [/b]
[/b]
[/b]
.gif.png[/b]]

getFieldValue(String ctlname)

String 类型String获取相应控件的值 比如:若String username =

ulb.getFieldValue("username"); 则为获取控件名为

username中的值.

getFileValue(String cltname)

String类型Byte[]获取上传组件文件的流以便存入到数据库中 例如:byte[]

filename1 = ulb.getFileValue(“filename1”);则为 获取上传

控件名为filename1中的上传文件流

getFilename(String ctlname)

String 类型String获取上传文件的文件名 比如: String filename2 =

ulb.getFilename(“filename1”); 则为获取上传控件名为

filename1中的上传文件的文件名

getContentType(String ctlname)

String 类型String获取上传文件类型 比如: String filetype2 =

ulb.getContentType(“filename1”); 则为获取上传控件名为

filename1中的上传文件的类型

getFileLength(String ctlname)

String 类型String获取上传文件的大小 比如: String filelength2 =

ulb.getFileLength(“filename1”); 则为 获取上传空间名为

filename1中的上传文件的大小

以下附上源码:

//upload javabean

package myupload;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.RandomAccessFile;

import java.util.Hashtable;

import java.util.Vector;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletInputStream;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;

public class UpLoadBean {

private HttpServletRequest request = null;

public UpLoadBean(HttpServletRequest request) {

this.request = request;

}

//方法重载

public Object getAttribute(String name) {

return request.getAttribute(name);

}

public java.util.Enumeration getAttributeNames() {

return request.getAttributeNames();

}

public java.lang.String getCharacterEncoding() {

return request.getCharacterEncoding();

}

public void setCharacterEncoding(String env) throws java.io.UnsupportedEncodingException {

request.setCharacterEncoding(env);

}

public int getContentLength() {

return request.getContentLength();

}

public int getLocalPort() {

return request.getLocalPort();

}

public String getLocalAddr() {

return request.getLocalAddr();

}

public String getLocalName() {

return request.getLocalName();

}

public int getRemotePort() {

return request.getRemotePort();

}

public java.lang.String getContentType() {

return request.getContentType();

}

public ServletInputStream getInputStream() throws java.io.IOException {

return request.getInputStream();

}

public java.util.Map getParameterMap() {

return request.getParameterMap();

}

public java.lang.String getProtocol() {

return request.getProtocol();

}

public java.lang.String getScheme() {

return request.getScheme();

}

public java.lang.String getServerName() {

return request.getServerName();

}

public int getServerPort() {

return request.getServerPort();

}

public java.io.BufferedReader getReader() throws java.io.IOException {

return request.getReader();

}

public java.lang.String getRemoteAddr() {

return request.getRemoteAddr();

}

public java.lang.String getRemoteHost() {

return request.getRemoteHost();

}

public void setAttribute(java.lang.String name, Object o) {

request.setAttribute(name, o);

}

public void removeAttribute(java.lang.String name) {

request.removeAttribute(name);

}

public java.util.Locale getLocale() {

return request.getLocale();

}

public java.util.Enumeration getLocales() {

return request.getLocales();

}

public boolean isSecure() {

return request.isSecure();

}

public RequestDispatcher getRequestDispatcher(String path) {

return request.getRequestDispatcher(path);

}

public java.lang.String getRealPath(String path) {

return request.getRealPath(path);

}

public java.lang.String getAuthType() {

return request.getAuthType();

}

public Cookie[] getCookies() {

return request.getCookies();

}

public long getDateHeader(java.lang.String name) {

return request.getDateHeader(name);

}

public java.lang.String getHeader(java.lang.String name) {

return request.getHeader(name);

}

public java.util.Enumeration getHeaders(java.lang.String name) {

return request.getHeaders(name);

}

public java.util.Enumeration getHeaderNames() {

return request.getHeaderNames();

}

public int getIntHeader(java.lang.String name) {

return request.getIntHeader(name);

}

public java.lang.String getPathInfo() {

return request.getPathInfo();

}

public java.lang.String getPathTranslated() {

return request.getPathTranslated();

}

public java.lang.String getContextPath() {

return request.getContextPath();

}

public java.lang.String getQueryString() {

return request.getQueryString();

}

public java.lang.String getRemoteUser() {

return request.getRemoteUser();

}

public boolean isUserInRole(java.lang.String role) {

return request.isUserInRole(role);

}

public java.security.Principal getUserPrincipal() {

return request.getUserPrincipal();

}

public java.lang.String getRequestedSessionId() {

return request.getRequestedSessionId();

}

public java.lang.String getRequestURI() {

return request.getRequestURI();

}

public java.lang.StringBuffer getRequestURL() {

return request.getRequestURL();

}

public java.lang.String getServletPath() {

return request.getServletPath();

}

public HttpSession getSession() {

return request.getSession();

}

public HttpSession getSession(boolean create) {

return request.getSession(create);

}

public boolean isRequestedSessionIdValid() {

return request.isRequestedSessionIdValid();

}

public boolean isRequestedSessionIdFromCookie() {

return request.isRequestedSessionIdFromCookie();

}

public boolean isRequestedSessionIdFromURL() {

return request.isRequestedSessionIdFromURL();

}

public boolean isRequestedSessionIdFromUrl() {

return request.isRequestedSessionIdFromUrl();

}

//重载结束

//实例化一个tool

UpLoadTools ultool = new UpLoadTools();

private String[] sourceFile = new String[255]; //源文件名

private String[] suffix = new String[255]; //文件后缀名

private String canSuffix = ".gif.jpg.jpeg.png"; //可上传的文件后缀名

private byte[] files = null; //上传文件数组

private ServletInputStream inputStream = null; //输入流

private int streamLenth = 0; //输入流长度

private FileOutputStream tmpfileStream = null; //临时文件

private RandomAccessFile randomFile = null; //以随机读写方式打开http临时流文件

private String[] description = new String[255]; //描述状态

private long size = 1024 * 1024 * 300; //限制大小 若为-1则不限制

// 保存名字/对象对应关系

private Hashtable fields = new Hashtable(); //hashtable

// 保存所有名字

private Vector names = new Vector(); //vector

//上传文件限制

public void setSuffix(String canSuffix) {

this.canSuffix = canSuffix;

}

//上传文件大小限制

public void setSize(long maxSize) {

this.size = maxSize;

System.out.println("新配置" + size + " || 传过来的参数:" + maxSize);

}

//上传文件主方法

public void getSourceFile() throws IOException {

inputStream = request.getInputStream();

//System.out.println(inputStream + "<br />");

//==============将上传文件存入临时文件=======================

String tmpfileName = null;

streamLenth = request.getContentLength();

tmpfileName = "c://temp//" + request.getSession().getId();

tmpfileStream = new FileOutputStream(tmpfileName);

//获取上传内容,并将其保存在临时文件中。

int bytesRead = 0, totalBytes = 0;

byte[] cnt;

while (totalBytes < streamLenth) {

cnt = new byte[256];

bytesRead =

inputStream.read(cnt, 0, 256); //中的方法在此字节输入流中从给定的偏移量开始将各字节读取到指定的 byte 数组中

totalBytes += bytesRead;

tmpfileStream.write(cnt);

}

tmpfileStream.close();

inputStream.close();

//现已将Http协议上传的内容全部写入了临时文件。以下的代码便可在服务器上对上传的内容进行解释

//======================临时文件写入完毕========================

randomFile = new RandomAccessFile(tmpfileName, "rw");

//System.out.println(randomFile + "<br />");

String theSingleDeli = randomFile.readLine(); //开始分界符

String theSingleend = theSingleDeli + "--";

//System.out.println(theSingleend);

int k = 0;

String line = "";

boolean flag = true;

long cntStartPoint = 0, cntEndPoint = 0;

int count = 0;

while (flag) {

line = randomFile.readLine();

if (line.indexOf("filename=/"") != -1) {

String filename = ultool.getFileName(line);

String filetype = ultool.getFileType(line);

String elementname = ultool.getElename(line);

//System.out.println("the filename and filetype and ename is :" + filename + "||" + filetype + "||" + elementname);

line = randomFile.readLine();

line = randomFile.readLine();

cntStartPoint = randomFile.getFilePointer();

boolean eofblock = false;

while (!eofblock) {

line = randomFile.readLine();

//System.out.println("the line is :" + line);

if (line.contains(theSingleDeli)) {

eofblock = true;

}

}

cntEndPoint = randomFile.getFilePointer() - line.length();

int cntlen = (int)(cntEndPoint - cntStartPoint);

System.out.println(cntlen + " || " + size);

if ((cntlen != -1) && (cntlen >= size)) {

description[count] = "上传文件过大!";

System.out.println("the description[" + count + "]" +

description[count]);

flag = false;

} else {

files = new byte[cntlen];

randomFile.seek(cntStartPoint);

randomFile.read(files, 0, cntlen);

//System.out.println("the length is :" + ultool.getFormat(cntlen));

String filelength = ultool.getFormat(cntlen);

upload up =

new upload(elementname, filetype, files, filename,

filelength);

names.add(up);

//System.out.println(files);

fields.put(elementname, count);

}

++count;

} else if ((k = line.indexOf("name=/"")) != -1) {

String elementname = ultool.getElename(line);

//System.out.println("the control name is :" + elementname);

line = randomFile.readLine();

line = randomFile.readLine();

fields.put(elementname, line.toString());

//System.out.println("the kongjian line is :" + line);

}

if (line.indexOf(theSingleend) != -1) {

flag = false;

}

}

randomFile.close();

//删除临时文件

File file = new File(tmpfileName);

file.delete();

//System.out.println(fields);

}

/**

* 获取上传文件名

* @param name 上传文件控件名

* @return

*/

public String getFilename(String name) {

if (name == null) {

return "上传文件有问题";

}

int index = (Integer)fields.get(name);

upload up2 = (upload)names.get(index);

return up2.filename;

}

/**

* 获取上传文件的大小

* @param name 上传文件控件名

* @return

*/

public String getFileLength(String name) {

if (name == null) {

return null;

} else {

int index = (Integer)fields.get(name);

upload up2 = (upload)names.get(index);

return up2.filelength;

}

}

/**

* 获取上传文件类型

* @param name 上传文件控件名

* @return

*/

public String getContentType(String name) {

if (name == null) {

return "上传文件有问题";

} else {

int index = (Integer)fields.get(name);

upload up2 = (upload)names.get(index);

return up2.Content_Type;

}

}

/**

* 获取上传文件Byte[]流

* @param name 上传文件控件名

* @return byte[]

*/

public byte[] getFileValue(String name) {

if (name == null) {

return null;

} else {

int index = (Integer)fields.get(name);

upload up2 = (upload)names.get(index);

return up2.value;

}

}

/**

* 获取指定空间的值

* @param fieldName 获取表单控件名

* @return String

*/

public String getFieldValue(String fieldName) {

if (fields == null || fieldName == null) {

return null;

}

return (String)fields.get(fieldName);

}

//判断上传文件的类型

public boolean canTransfer(int i) {

suffix[i] = suffix[i].toLowerCase();

//System.out.println("the suffix["+i+"] is :"+suffix[i]);

if (sourceFile[i].equals("") ||

(!(canSuffix.indexOf("." + suffix[i]) >= 0))) {

description[i] = "文件类型不允许!";

return false;

} else {

return true;

}

}

class upload {

// 控件名称

String elementname = null;

// 类型

String Content_Type = null;

// 内容

byte[] value = null;

// 文件名

String filename = null;

// 文件大小

String filelength = null;

upload(String elementname, String Content_Type, byte[] value,

String filename, String filelength) {

this.elementname = new String(elementname);

if (Content_Type != null)

this.Content_Type = new String(Content_Type.trim());

if (filename != null)

this.filename = new String(filename.trim());

if (value != null)

this.value = value;

if (filelength != null)

this.filelength = filelength;

}

}

class upFileInfo {

/**

* 得到对象

* @param index 索引

* @return 对象

*/

upload getUpload(int index) {

if ((index >= 0) && (names.size() > index)) {

return (upload)names.elementAt(index);

} else {

return null;

}

}

/**

* 读取内容

* @param index 索引

* @return 内容

*/

byte[] getValue(int index) {

upload up = getUpload(index);

if (up == null) {

return null;

} else {

return up.value;

}

}

/**

* 读取文件名

* @param index 索引

* @return 文件名

*/

String getFilename(int index) {

upload up = getUpload(index);

if (up == null) {

return null;

} else {

return up.filename;

}

}

/**

* 读取文件长度

* @param index 索引

* @return 文件长度

*/

String getFileLength(int index) {

upload up = getUpload(index);

if (up == null) {

return null;

} else {

return up.filelength;

}

}

/**

* 读取文件类型

* @param index 索引

* @return 文件类型

*/

String getFileType(int index) {

upload up = getUpload(index);

if (up == null) {

return null;

} else {

return up.Content_Type;

}

}

/**

* 读取控件名

* @param index 索引

* @return 控件名

*/

String getElementName(int index) {

upload up = getUpload(index);

if (up == null) {

return null;

} else {

return up.elementname;

}

}

}

}

//get function

package myupload;

public class UpLoadTools {

public UpLoadTools() {

}

/**

* 获取文件名称

* @param str String 一行字符串

* @return String

*/

public String getFileName(String str) {

String pathName = str.substring(str.indexOf("filename="));

int startIndex = pathName.indexOf("filename=/"") + 10;

int endIndex = pathName.lastIndexOf("/"");

if ((endIndex - startIndex) == 0)

return "";

else {

startIndex = pathName.lastIndexOf("//") + 1;

if ((startIndex != -1) && (startIndex != 0)) {

pathName = pathName.substring(startIndex, endIndex);

pathName=this.convert(pathName);

} else {

return "";

}

}

return pathName;

}

/**

* 获取文件类型

* @param str 一行文件

* @return String

*/

public String getFileType(String str) {

String typeName = str.substring(str.indexOf("filename="));

int startIndex = typeName.indexOf("filename=/"") + 10;

int endIndex = typeName.lastIndexOf("/"");

if ((endIndex - startIndex) == 0)

return "";

else {

startIndex = typeName.lastIndexOf(".") + 1;

if ((startIndex != -1) && (startIndex != 0)) {

typeName = typeName.substring(startIndex, endIndex);

} else {

return "";

}

}

return typeName;

}

/**

* 获取文件完整类型

* @param str String 一行所读出的字符串

* @return String

*/

public String getType(String str) {

String typeName = null;

typeName = str.substring(14);

return typeName;

}

/**

* 获取控件名

* @param str String 一行string

* @return String

*/

public String getElename(String str) {

String elementName = null;

String tempStr = str.substring(str.indexOf("name=/"") + 6);

elementName = tempStr.substring(0, tempStr.indexOf("/""));

return elementName;

}

/**

* 四舍五入

* @param f double 类型,要进行四舍五入的数字

* @param position 要保留小数位的个数

* @return String

* @throws Exception

*/

public String round(double f, int position) throws Exception {

String sf = String.valueOf(f);

int i = sf.indexOf(".");

String s1 = "", s2 = "";

if (sf.substring(i + 1).length() <= position) {

return String.valueOf(f);

}

if (position == 0) {

s1 = sf.substring(i - 1, i);

s2 = sf.substring(i + position + 1, i + position + 2);

if (Integer.parseInt(s2) >= 5) {

s1 = String.valueOf(Integer.parseInt(s1) + 1);

}

return sf.substring(0, i - 1) + s1;

} else {

s1 = sf.substring(i + position, i + position + 1);

s2 = sf.substring(i + position + 1, i + position + 2);

if (Integer.parseInt(s2) >= 5) {

s1 = String.valueOf(Integer.parseInt(s1) + 1);

}

return sf.substring(0, i + position) + s1;

}

}

/**

* 解决中中文显示乱码

* @param str String 文件名

* @return String

*/

public String convert(String str) {

try {

byte[] bytesStr = str.getBytes("ISO-8859-1");

return new String(bytesStr, "gb2312");

} catch (Exception e) {

return str;

}

}

/**

* 得到上传文件大小

* @param content String 上传文件流

* @return String

*/

public String getFormat(int content) {

String format = null;

try {

if (content > 1024 * 1024) {

format = this.round(content / 1024 / 1024, 2) + "MB";

} else if (content > 1024 && content < 1024 * 1024) {

format = this.round(content / 1024, 2) + "KB";

} else {

format = content + "Bytes";

}

} catch (Exception e) {

// TODO

e.getMessage();

format = "计算出错";

}

return format;

}

/**

* 获取网页头部信息

* @param line 获取分隔符

* @return boolean

*/

public boolean getHeader(String line){

boolean flag=false;

String Str=line.substring(1,29);

if(Str.equals("----------------------------")){

flag=true;

}else{

flag=false;

}

return flag;

}

}

//使用方法

UpLoadBean ulb = new UpLoadBean(request);

ulb.setSize(1024*1024);

ulb.getSourceFile();

String username = ulb.getFieldValue("username");

String userpwd = ulb.getFieldValue("userpwd");

String pfile = "filename1";

byte[] filename1 = ulb.getFileValue(pfile);

String filename = ulb.getFilename(pfile);

String filetype = ulb.getContentType(pfile);

String filelength = ulb.getFileLength(pfile);

String pfile1 = "filename2";

byte[] filename12 = ulb.getFileValue(pfile1);

String filename2 = ulb.getFilename(pfile1);

String filetype2 = ulb.getContentType(pfile1);

String filelength2 = ulb.getFileLength(pfile1);

try {

InitialContext ic = new InitialContext();

DataSource ds = (DataSource)ic.lookup("jdbc/oldwolfDS");

Connection conn = ds.getConnection();

String sql="insert into uptable (username,userpwd,pic1) values (?,?,empty_blob())";

//第一步插入一个空Blob字段

PreparedStatement ps = conn.prepareStatement(sql);

ps.setString(1, username);

ps.setString(2, userpwd);

ps.executeUpdate();

ps.close();

//第二步取出数据库表中的Blob字段。

Statement st = conn.createStatement();

String sql1="select pic1 from uptable where username='" + username + "' for update";

ResultSet rs = st.executeQuery(sql1);

rs.next();

Blob blob1 = (Blob)rs.getBlob("pic1");

//Blob更新操作:设置输出流。

OutputStream os1 = blob1.setBinaryStream(0);

//System.out.println("the sql is :"+sql+" || the sql1 is :"+sql1+" || the blob1 is :"+blob1+" || the blob2 is :"+blob2+" || the os1 is :"+os1+" || the os2 is :"+os2);

os1.write(filename1);

os1.close();

//Blob更新操作:通过输出流写入内容。

ps = conn.prepareStatement("update uptable set pic1=? where username='" +username + "'");

ps.setBlob(1, blob1);

conn.commit();

ps.close();

rs.close();

st.close();conn.close();

} catch (Exception e) {

e.printStackTrace();

}

这个程序是我自己写的,还有些问题,比如说上传文件大小的限制,类型的限制还没做好.希望大家一起来完成.

希望这个程序能对初学者有所帮组
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: