2010.09.21——— struts2 上传 并且存blob到oracle

2010.09.21——— struts2 上传 并且存blob到oracle

需求:上传图片 把图片保存到指定文件夹 并且在数据库里面即保存路径也要保存图片,经理的要求 没办法啊

需要的jar包:ognl.jar,xwork-core.jar,struts2-core.jar,freemarker.jar,commons-logging.jar,commons-fileupload.jar,Commons-io.jar(注意必须对应相应的版本jar类包)

要在struts.xml里面添加 <constant name="struts.multipart.saveDir" value="/tmp"/>
用来设置临时文件路径

用struts2的上传下载 可以在struts.xml里面添加一个上传下载的拦截器fileUploadStack,来设置文件类型,和文件大小

[b]1. html 上传的form表单[/b]

<form name="add" method="post"  enctype="multipart/form-data" action=""> 
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="grid mar2" id="tblSort01">

<tr>
<td width="22%" align="right" class="table_color">工程编码:</td>
<td width="66%"><input class="input_text" type="text" name="sc.gcbm" id="GCBM" readonly size="75"></td>
<td width="12%" align="left" class="table_color"></td>
</tr>
<tr>
<td width="22%" align="right" class="table_color">项目名称:</td>
<td width="66%"><input class="input_text" type="text" name="sc.xmmc" id="XMMC" readonly size="75"></td>
<td width="12%" align="left" class="table_color"></td>
</tr>
<tr>
<td width="22%" align="right" class="table_color">选择上传的文件:</td>
<td width="66%"><input type="file" name="file" id="file" size="50" class="input_file"></td>
<td width="12%" align="left" class="table_color"></td>
</tr>
<tr>
<td align="right" class="table_color">图片描述:</td>
<td><textarea name="sc.mark" class="textarea_text" rows="10" id="mark" ></textarea></td>
<td align="left" class="table_color"></td>
</tr>
<tr>
<td colspan="3" align="center" ><p> </p>
<p>
<a href='#' onclick="addImg();return false;" class="rbutton"><span>提交</span></a>   

<p> </p></td>
</tr>
</table>
</form>


[color=red]注意<input type="file" name="file" id="file" size="50" class="input_file">他的name决定了后台三个属性的名字[/color]

[b]2. action[/b]


package shipin.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.util.Streams;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import shipin.pojo.SP_Camera;
import shipin.service.SP_CameraService;

import com.opensymphony.xwork2.ActionSupport;
public class SP_CameraAction extends ActionSupport{
/**
* 关于文件上传
* 1>File对应的表单中file名称其中影响的三个字段为file的表单名称为:xxx,xxxFileName,xxxContentType
* @author Administrator
*
*/
// 上传文件域对象
private SP_Camera sc;
//代表上传文件的file对象
private File file;
//上传文件名
private String fileFileName;
//上传文件的类型
private String fileContentType;
//上传图片的service对象
private SP_CameraService sp_CameraService;
//根据工程编码查询的图片集合
private List<SP_Camera> list;
// 保存文件的目录路径(通过依赖注入)
private String savePath;



//增加一张图片
public String addImg(){

log.info(file.getName());
//得到当前时间自1970年1月1日0时0分0秒开始流逝的毫秒数,将这个毫秒数作为上传新的文件名

long now = new Date().getTime();
//得到保存上传文件的目录的真实路径
String path = ServletActionContext.getServletContext().getRealPath(this.getSavePath());
System.out.println("得到保存上传文件的目录的真实路径:"+path);
File dir = new File(path);
//如果这个目录不存在,则创建它
if(!dir.exists()){
dir.mkdir();
}

int index = fileFileName.lastIndexOf('.');
String str = fileFileName.substring(0,index);
log.info(str);
//判断上传文件名是否有扩展名,以时间戳作为新的文件名
if(index!=-1){
sc.setImgName(now+fileFileName.substring(index));// = now+fileFileName.substring(index);
}else{
sc.setImgName(Long.toString(now));
}

BufferedOutputStream bos = null;
BufferedInputStream bis = null;

//读取保存在临时目录下的上传文件,写入新的文件中
try {
FileInputStream fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(new File(dir,sc.getImgName()));
bos = new BufferedOutputStream(fos);
//Streams.copy(bis,bos,true);
byte[] buf = new byte[4096];
int len=-1;

while((len=bis.read(buf))!=-1){
bos.write(buf,0,len);
}
bis.close();
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// PicCompression.proce(path+"\\"+sc.getImgName(),400, 300, 1, "");
sc.setImgOldName(str);
sc.setUserId(1); //---------------这个值以后从session中获得,暂时写为1;
//sc.setImgRealPagh(path+"\\"+sc.getImgName());
sc.setImgPath("\\uploadDir\\"+sc.getImgName());
this.sp_CameraService.saveImg(sc);
this.list = this.sp_CameraService.findImgByGcbm(sc.getGcbm());
return SUCCESS;
}



}



[b]3. sturts.xml 配置[/b]

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.i18n.encoding" value="utf-8"></constant>
<!-- 临时路径-->
<constant name="struts.multipart.saveDir" value="/tmp"/>
<!-- extends说明该配置文件继承自struts-default.xml -->
<package name="action2" extends="struts-default" >
<!-- action 的 name属性是必需的,其他属性都是可选的。 -->
<global-results>
<result name="exception">msg/error.jsp</result>
</global-results>
<!-- 全局异常映射定义 -->
<global-exception-mappings>

<exception-mapping result="exception" exception="java.lang.Exception"/>
</global-exception-mappings>



<!-- 视频配置 -->

<!-- 抓图 -->
<!-- 将一张图片保存到某个工程下,跳转到图片管理界面 -->
<action name="addImg" class="shipin.action.SP_CameraAction" method="addImg">
<!-- 动态设置Action中的savePath属性的值 -->
<param name="savePath">upload</param>
<result name="success">shipinxinxi/queryImg.jsp</result>
</action>


<!-- 抓图 -->
</package>




</struts>


这时 可以选择加上fileUpload拦截器了

<action name="addImg"  class="shipin.action.SP_CameraAction" method="addImg">
<interceptor-ref name="fileUpload">
<!-- 配置允许上传的文件类型,多个用","分隔 -->
<param name="allowedTypes">
image/bmp,image/png,image/gif,image/jpeg,image/jpg
</param>
<!-- 配置允许上传的文件大小,单位字节 -->
<param name="maximumSize">102400</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />

<!-- 动态设置Action中的savePath属性的值 -->
<param name="savePath">upload</param>
<result name="success">shipinxinxi/queryImg.jsp</result>
</action>



但是 上面是一般的都这样写 但是 因为我后来要把图片当成blob保存到数据库中,所以

[color=red]在java中 把private String savePath; 去掉 我不注入了,我自己直接写:

String path = ServletActionContext.getServletContext().getRealPath("uploadDir");

struts.xml里面把<param name="savePath">upload</param> 去掉[/color]

下面是 Dao 实现把图片存为blob

/**
* 往数据库中插入一张图片,需要先从客户端上传一张图片到服务器上,保存图片原有名称和现在名称
* 图片保存在应用的指定位置下,数据库中保存的是相对路径,也需要把这张图片保存到数据库里
*
*/
public void insertImg(final SP_Camera sc){
String sqlId = "select sp_camera_seq.nextval from dual";
log.info(sqlId);
//获得id的值
int id = this.jdbcTemplate.queryForInt(sqlId);
//blob类型的要先插入一条空的数据 然后在更新
String sql = "insert into sp_camera values("+id+",empty_blob(),'"+sc.getImgName()+"',sysdate,'"+sc.getMark()+"',"+sc.getUserId()+",'"+sc.getGcbm()+"','"+sc.getImgPath()+"','"+sc.getImgOldName()+"')";
log.info(sql);
this.jdbcTemplate.update(sql);

final String querysql = "select img from sp_camera where id ="+id+" for update";
log.info(querysql);

this.jdbcTemplate.execute(new ConnectionCallback(){

public Object doInConnection(Connection con) throws SQLException,DataAccessException {
con.setAutoCommit(false);
Statement st = con.createStatement();
//用 for update 方式锁定数据行
ResultSet rs = st.executeQuery(querysql);
try {
if(rs.next()){
//得到java.sql.blob 对象
BLOB blob = (BLOB) rs.getBlob(1);
//得到数据库的输出流
OutputStream outStream = blob.getBinaryOutputStream();
//这里用一个文件模拟输入流.
String path = ServletActionContext.getServletContext().getRealPath("uploadDir");//这个和前面的一样
log.info(path);
File file = new File(path+"\\"+sc.getImgName());
InputStream inStream = new FileInputStream(file);
//将输入流写到输出流
byte[] b = new byte[blob.getBufferSize()];
int len = 0 ;
while((len=inStream.read(b))!=-1){
outStream.write(b,0,len);
}
inStream.close();
outStream.flush();
outStream.close();
con.commit();//之前因为没有commit 所以blob一直不能写入数据库中
con.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

});
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值