发信人: gznovice()
整理人: zjxyz(2002-01-21 08:15:41), 站内信件
|
upload file及入库(原始版)
实现方式是调用已有的upload软件包,将upload的文件存在临时目录内,再输入数 据库,以下的例子仅代参考,
并未优化,但不存在中文乱码问题.例子实现上传图像文件,并显示出来。
(虽然代码不长,但调试起来颇麻烦,请注意入库及出库的参数次序,否则......)
平台:IE5,NT4,TOMCAT3.1,ORACLE8.0.5,JDK1.2.2
(I'm still looking for a job in Guangzhou. Contact me by zhiqiang_z@16 3.net)
sql:
create table imgfile(name varchar2(50),afile long raw,type varchar2(50 ));
Upload2.java(upload及入库servlet):
import java.net.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import com.f2s.zzq.MultipartRequest;
public class UploadTest2 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head><title>Zzq's Test Area</title></head>");
out.println("<FORM ACTION=\"\" ENCTYPE=\"multipart/form-data\" METHOD= \"POST\" >");
out.println("Which file do you want to upload? <INPUT TYPE=\"FILE\" NA ME=\"file\">");
out.println("<INPUT TYPE=\"SUBMIT\"></FORM>");
out.println("</html>");
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html; charset=GB2312");
PrintWriter out = res.getWriter();
File adir=new File((File)getServletContext().getAttribute("javax.s ervlet.context.tempdir"),req.getSession().getId());
if(adir.exists())
{
/*
File[] filelist=adir.listFiles();
for(int i=0;i<filelist.length;i++)
filelist[i].delete();
adir.delete();
*/
}
else if(!adir.mkdir())
{
System.out.println("Not Writable");
return;
}
try {
// Blindly take it on faith this is a multipart/form-data reques t
// Construct a MultipartRequest to help read the information.
// Pass in the request, a directory to saves files to, and the
// maximum POST size we should attempt to handle.
// Here we (rudely) write to the server root and impose 5 Meg li mit.
MultipartRequest multi =
new MultipartRequest(req, adir.toString(), 5 * 1024 * 1024);
out.println("<HTML>");
out.println("<head><title>Zzq's Test Area</title></head>");
// Print the parameters we received
out.println("<pre>");
Enumeration files = multi.getFileNames();
if (files.hasMoreElements()) {//only the first file is handled.
String name = (String)files.nextElement();
String filename = multi.getFilesystemName(name);
String type = multi.getContentType(name);
File f = multi.getFile(name);
out.println("name: " + name);
out.println("filename: " + filename);
out.println("type: " + type);
intoDB(f,type);
if (f != null) {
out.println("length: " + f.length());
out.println();
}
out.println("</PRE>");
out.println("<img src=\"ImageServlet?name="+URLEncoder.encode( filename)+"\" />");
}
}
catch (Exception e) {
e.printStackTrace(out);
}
finally{/*
if(adir.exists())
{File[] filelist=adir.listFiles();
for(int i=0;i<filelist.length;i++)
filelist[i].delete();
adir.delete();
}*/
}
out.println("</HTML>");
}
private void intoDB(File afile,String type) throws FileNotFoundExcepti on,IOException
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(ClassNotFoundException e)
{
System.out.println("JDBC Driver not found"+e.getMessage());
return;
}
try
{
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168. 1.13:1521:orcl",
"scott", "tiger");
PreparedStatement stmnt = con.prepareStatement("insert into imgfile(af ile,name,type) values(?,?,?)");
FileInputStream instream=new FileInputStream(afile);
stmnt.setBinaryStream(1, instream,(int)afile.length()); //The sequence is very important here!!!!!!
System.out.println(afile.length());
stmnt.setString(2,afile.getName());
System.out.println(afile.getName());
stmnt.setString(3,type);
System.out.println(type);
stmnt.execute();
stmnt.close();
con.close();
instream.close();
}catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
}
ImageServlet.java(出库,并显示):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
public class ImageServlet extends HttpServlet {
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if((request.getParameter("name")==null)||(request.getParameter("name") .equals("")))
{
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("No image found");
return;
}
ResultSet result=null;
byte [] bytes;
String type;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(ClassNotFoundException e) {}
try
{
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168. 1.13:1521:orcl",
"scott", "tiger");
PreparedStatement stmnt = con.prepareStatement("select afile,type from imgfile where name = ? ");
stmnt.setString(1,new String(request.getParameter("name").getBytes("IS O8859_1")));
System.out.println(new String(request.getParameter("name").getBytes("I SO8859_1")));
result=stmnt.executeQuery();
if(result.next())
{
bytes = result.getBytes (1);//The sequence is very important he re!!!!!!
type=result.getString(2);
}
else
{
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("No image found");
return;
}
response.setContentType(type);
ServletOutputStream out = response.getOutputStream();
out.write(bytes);
out.close();
stmnt.close();
con.close();
}catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
}
//////////////////begin////////////////////////
以下为Upload软件包(来自http://www.servlets.com/resources/com.oreilly.s ervlet/index.html)
package com.f2s.zzq;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.servlet.ServletRequest;
// Referenced classes of package com.oreilly.servlet:
// MultipartInputStreamHandler, UploadedFile
public class MultipartRequest
{
public MultipartRequest(ServletRequest request, String saveDirecto ry)
throws IOException
{
this(request, saveDirectory, 0x100000);
}
public MultipartRequest(ServletRequest request, String saveDirecto ry, int maxPostSize)
throws IOException
{
parameters = new Hashtable();
files = new Hashtable();
if(request == null)
throw new IllegalArgumentException("request cannot be null ");
if(saveDirectory == null)
throw new IllegalArgumentException("saveDirectory cannot b e null");
if(maxPostSize <= 0)
throw new IllegalArgumentException("maxPostSize must be po sitive");
req = request;
dir = new File(saveDirectory);
maxSize = maxPostSize;
if(!dir.isDirectory())
throw new IllegalArgumentException("Not a directory: " + s aveDirectory);
if(!dir.canWrite())
{
throw new IllegalArgumentException("Not writable: " + save Directory);
}
else
{
readRequest();
return;
}
}
public Enumeration getParameterNames()
{
return parameters.keys();
}
public Enumeration getFileNames()
{
return files.keys();
}
public String getParameter(String name)
{
try
{
String param = (String)parameters.get(name);
if(param.equals(""))
return null;
else
return param;
}
catch(Exception _ex)
{
return null;
}
}
public String getFilesystemName(String name)
{
try
{
UploadedFile file = (UploadedFile)files.get(name);
return file.getFilesystemName();
}
catch(Exception _ex)
{
return null;
}
}
public String getContentType(String name)
{
try
{
UploadedFile file = (UploadedFile)files.get(name);
return file.getContentType();
}
catch(Exception _ex)
{
return null;
}
}
public File getFile(String name)
{
try
{
UploadedFile file = (UploadedFile)files.get(name);
return file.getFile();
}
catch(Exception _ex)
{
return null;
}
}
protected void readRequest()
throws IOException
{
String type = req.getContentType();
if(type == null || !type.toLowerCase().startsWith("multipart/f orm-data"))
throw new IOException("Posted content type isn't multipart /form-data");
int length = req.getContentLength();
if(length > maxSize)
throw new IOException("Posted content length of " + length + " exceeds limit of " + maxSize);
String boundary = extractBoundary(type);
if(boundary == null)
throw new IOException("Separation boundary was not specifi ed");
MultipartInputStreamHandler in = new MultipartInputStreamHandl er(req.getInputStream(), boundary, length);
String line = in.readLine();
if(line == null)
throw new IOException("Corrupt form data: premature ending ");
if(!line.startsWith(boundary))
throw new IOException("Corrupt form data: no leading bound ary");
for(boolean done = false; !done; done = readNextPart(in, bound ary));
}
protected boolean readNextPart(MultipartInputStreamHandler in, Str ing boundary)
throws IOException
{
String line = in.readLine();
if(line == null)
return true;
String dispInfo[] = extractDispositionInfo(line);
String disposition = dispInfo[0];
String name = dispInfo[1];
String filename = dispInfo[2];
line = in.readLine();
if(line == null)
return true;
String contentType = extractContentType(line);
if(contentType != null)
{
line = in.readLine();
if(line == null || line.length() > 0)
throw new IOException("Malformed line after content ty pe: " + line);
}
else
{
contentType = "application/octet-stream";
}
if(filename == null)
{
String value = readParameter(in, boundary);
parameters.put(name, value);
}
else
{filename=new String(filename.getBytes("ISO8859_1"));
readAndSaveFile(in, boundary, filename);
if(filename.equals("unknown"))
files.put(name, new UploadedFile(null, null, null));
else
files.put(name, new UploadedFile(dir.toString(), filen ame, contentType));
}
return false;
}
protected String readParameter(MultipartInputStreamHandler in, Str ing boundary)
throws IOException
{
StringBuffer sbuf = new StringBuffer();
String line;
while((line = in.readLine()) != null)
{
if(line.startsWith(boundary))
break;
sbuf.append(line + "\r\n");
}
if(sbuf.length() == 0)
{
return null;
}
else
{
sbuf.setLength(sbuf.length() - 2);
return sbuf.toString();
}
}
protected void readAndSaveFile(MultipartInputStreamHandler in, Str ing boundary, String filename)
throws IOException
{
File f = new File(dir + File.separator + filename);
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream out = new BufferedOutputStream(fos, 8192) ;
byte bbuf[] = new byte[0x19000];
boolean rnflag = false;
int result;
while((result = in.readLine(bbuf, 0, bbuf.length)) != -1)
{
if(result > 2 && bbuf[0] == 45 && bbuf[1] == 45)
{
String line = new String(bbuf, 0, result, "ISO-8859-1" );
if(line.startsWith(boundary))
break;
}
if(rnflag)
{
out.write(13);
out.write(10);
rnflag = false;
}
if(result >= 2 && bbuf[result - 2] == 13 && bbuf[result - 1] == 10)
{
out.write(bbuf, 0, result - 2);
rnflag = true;
}
else
{
out.write(bbuf, 0, result);
}
}
out.flush();
out.close();
fos.close();
}
private String extractBoundary(String line)
{
int index = line.indexOf("boundary=");
if(index == -1)
{
return null;
}
else
{
String boundary = line.substring(index + 9);
boundary = "--" + boundary;
return boundary;
}
}
private String[] extractDispositionInfo(String line)
throws IOException
{
String retval[] = new String[3];
String origline = line;
line = origline.toLowerCase();
int start = line.indexOf("content-disposition: ");
int end = line.indexOf(";");
if(start == -1 || end == -1)
throw new IOException("Content disposition corrupt: " + or igline);
String disposition = line.substring(start + 21, end);
if(!disposition.equals("form-data"))
throw new IOException("Invalid content disposition: " + di sposition);
start = line.indexOf("name=\"", end);
end = line.indexOf("\"", start + 7);
if(start == -1 || end == -1)
throw new IOException("Content disposition corrupt: " + or igline);
String name = origline.substring(start + 6, end);
String filename = null;
start = line.indexOf("filename=\"", end + 2);
end = line.indexOf("\"", start + 10);
if(start != -1 && end != -1)
{
filename = origline.substring(start + 10, end);
int slash = Math.max(filename.lastIndexOf(47), filename.la stIndexOf(92));
if(slash > -1)
filename = filename.substring(slash + 1);
if(filename.equals(""))
filename = "unknown";
}
retval[0] = disposition;
retval[1] = name;
retval[2] = filename;
return retval;
}
private String extractContentType(String line)
throws IOException
{
String contentType = null;
String origline = line;
line = origline.toLowerCase();
if(line.startsWith("content-type"))
{
int start = line.indexOf(" ");
if(start == -1)
throw new IOException("Content type corrupt: " + origl ine);
contentType = line.substring(start + 1);
}
else
if(line.length() != 0)
throw new IOException("Malformed line after disposition: " + origline);
return contentType;
}
private static final int DEFAULT_MAX_POST_SIZE = 0x100000;
private ServletRequest req;
private File dir;
private int maxSize;
private Hashtable parameters;
private Hashtable files;
}
**************************************
package com.f2s.zzq;
import java.io.IOException;
import javax.servlet.ServletInputStream;
// Referenced classes of package com.oreilly.servlet:
// MultipartRequest, UploadedFile
class MultipartInputStreamHandler
{
public MultipartInputStreamHandler(ServletInputStream in, String b oundary, int totalExpected)
{
buf = new byte[8192];
this.in = in;
this.boundary = boundary;
this.totalExpected = totalExpected;
}
public String readLine()
throws IOException
{
StringBuffer sbuf = new StringBuffer();
int result;
do
{
result = readLine(buf, 0, buf.length);
if(result != -1)
sbuf.append(new String(buf, 0, result, "ISO-8859-1"));
}
while(result == buf.length);
if(sbuf.length() == 0)
{
return null;
}
else
{
sbuf.setLength(sbuf.length() - 2);
return sbuf.toString();
}
}
public int readLine(byte b[], int off, int len)
throws IOException
{
if(totalRead >= totalExpected)
return -1;
int result = in.readLine(b, off, len);
if(result > 0)
totalRead += result;
return result;
}
ServletInputStream in;
String boundary;
int totalExpected;
int totalRead;
byte buf[];
}
*************************************************************
package com.f2s.zzq;
import java.io.File;
class UploadedFile
{
UploadedFile(String dir, String filename, String type)
{
this.dir = dir;
this.filename = filename;
this.type = type;
}
public String getContentType()
{
return type;
}
public String getFilesystemName()
{
return filename;
}
public File getFile()
{
if(dir == null || filename == null)
return null;
else
return new File(dir + File.separator + filename);
}
private String dir;
private String filename;
private String type;
}
//////////////////////end////////////////////////
(I'm still looking for a job in Guangzhou. Contact me by zhiqiang_z@16 3.net)
-- ※ 来源:.月光软件站 http://www.moon-soft.com.[FROM: 210.75.34.194]
|
|