当前位置: 技术问答>java相关
如何用jsp实现文件上载的问题?
来源: 互联网 发布时间:2017-03-30
本文导语: 如何实现上载呢?上载后的文件是放在数据库里,还是存成文件呢? | Untitled Document | import java.sql.*; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import...
如何实现上载呢?上载后的文件是放在数据库里,还是存成文件呢?
|
Untitled Document
|
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.jspsmart.upload.*;
/**
*
Title:
*
Description:
*
Copyright: Copyright (c) 2002
*
Company:
* @author not attributable
* @version 1.0
*/
public class UpLoad extends HttpServlet{
public UpLoad() {
}
private ServletConfig config;
/**
* Init the servlet
*/
final public void init(ServletConfig config) throws ServletException {
this.config = config;
}
final public ServletConfig getServletConfig() {
return config;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("============UpLoad begin ddd=============");
String id=null;
SmartUpload mySmartUpload = new SmartUpload();
PrintWriter out = response.getWriter();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: "+e.getMessage());
}
try{
//Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@10.216.0.2:1521:ORCL","dms","dms");
conn.setAutoCommit(false);//关闭自动提交,以提高性能。
Statement stmt=conn.createStatement();
// Initialization
mySmartUpload.initialize(config, request, response);
mySmartUpload.setMaxFileSize(500 * 1024);
// Upload
mySmartUpload.upload();
Enumeration enumer=mySmartUpload.getRequest().getParameterNames();
while(enumer.hasMoreElements()){
String key=(String) enumer.nextElement();
String[] values=mySmartUpload.getRequest().getParameterValues(key);
if(key.equals("id")){ //得到各个的内容
id=values[0];
}
}
//取得文件和文件名
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
String fileName=myFile.getFileName();
if(!myFile.isMissing()){
//save data
//myFile.saveAs("/upload/" + fileName);
//mySmartUpload.save("/upload/" + fileName);
myFile.saveAs(fileName,mySmartUpload.SAVE_PHYSICAL);
System.out.println
java.io.File file=new java.io.File(fileName);
java.io.InputStream inStream=new java.io.FileInputStream(file);
int fileSize=myFile.getSize();
byte[] bytes = new byte[fileSize];
String strSql="insert into zyw_test(id,name,content) values('"+id+"','"+fileName+"',empty_blob())";
stmt.execute(strSql);
ResultSet rs=stmt.executeQuery("select content from zyw_test where id='"+id+"' for update ");
if (rs.next()){
oracle.sql.BLOB blob = ((oracle.jdbc.OracleResultSet)rs).getBLOB("content");
OutputStream outStream = blob.getBinaryOutputStream();
inStream.read(bytes);
for(int i = 0; i