利用jspsmart上传文件

本文介绍了一种利用JSP实现文件上传的方法,包括前端form表单提交与后端文件流读取处理的过程。通过具体代码示例展示了如何设置文件大小限制及文件类型的过滤,并直接读取文件流进行数据库存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.upFile.jsp在页面提交form代码参照一下内容
<script language="javascript">
function SaveItem(type){
var str = document.all.ON_SEQ.value;
var dd=str.indexOf(".")
var type = document.all.ON_SEQ.value.substring(dd+1, str.length);
if(type == "xls"){
document.forms('clientForm').action="upFileSave.jsp?type=" + type;
document.forms('clientForm').submit();
return;
} else{
return alert("请选择上传excel文件!");
}
}
</script>

<form name="clientForm" method="POST" action="upFileSave.jsp" id="clientForm" enctype="multipart/form-data">
<input type="file" name="file">
<a href="javascript:SaveItem(0)>上传 </a>
</form>

2.upFileSave.jsp,直接读取文件流,不在服务器保留上传文件

try {
//实例化上载bean
com.jspsmart.upload.SmartUpload mySmartUpload = new com.jspsmart.upload.SmartUpload();
//初始化
mySmartUpload.initialize(pageContext);
//设置上载的最大值
mySmartUpload.setMaxFileSize(5 * 1024 * 1024);
//设置上传文件类型
//mySmartUpload.setAllowedFilesList("xls");
//上载文件
mySmartUpload.upload();

String ordernoid = StringAssistant.getStringClear(mySmartUpload.getRequest().getParameter("type"));

com.jspsmart.upload.File lo_File = mySmartUpload.getFiles().getFile(0);

byte[] fileContent = new byte[(int) lo_File.getSize()];
for (int k = 0; k < (int) lo_File.getSize(); k++) {
fileContent[k] = lo_File.getBinaryData(k);
}
InputStream fs = null;
if (!lo_File.isMissing()) {
fs = new ByteArrayInputStream(fileContent);

//数据库相关操作....
//手动提交
conn.setAutoCommit(false);
sql = "insert into contsub_upload_file(id,FILE_NAME,FILE_CONTENT) values (?,?,?,)";
pre = null;
pre = conn.prepareStatement(sql);
long id =SequenceMaker.getSequence("id", "contsub_upload_file_seq");
pre.setLong(1, id);
pre.setString(2,lo_File.getFileName());
pre.setBlob(3, oracle.sql.BLOB.empty_lob());
pre.executeUpdate();
pre = null;
rs = null;
pre = conn.prepareStatement("SELECT FILE_CONTENT FROM contsub_upload_file WHERE id = " + id + " for update");
rs = pre.executeQuery();
if (rs.next())
{
oracle.sql.BLOB fc = (oracle.sql.BLOB) rs.getBlob("FILE_CONTENT");
java.io.OutputStream binOut = fc.getBinaryOutputStream();
java.io.BufferedOutputStream out1 = new java.io.BufferedOutputStream(binOut);
java.io.BufferedInputStream in = new java.io.BufferedInputStream(fs);
int c;
while ((c = in.read()) != -1)
{
out1.write(c);
}
in.close();
out1.close();
}
rs.close();
pre.close();
}

} catch (Exception er) {
System.out.println(er);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值