struts2 文件存储到数据库

ruiqinzhen 2010-04-20 04:17:27
我的主要问题是struts2文件已经可以上传到服务器端的 一个文件夹中了,但是我现在要把文件存到数据库中,数据库中是用byte[]数组来存储的,而拿过来的文件是struts2的File类型,请问有谁知道怎么把struts2的File类型转化成byte[]数组,存储到数据库中呢 。。谢了
...全文
150 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhiichen 2011-06-07
  • 打赏
  • 举报
回复
File --> InputStream
InputStream in = new InputStream(new FileInputStream(File));

InputStream --> File
public void inputstreamtofile(InputStream ins,File file){
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
}
zhiichen 2011-06-07
  • 打赏
  • 举报
回复
说有getInputStream()方法的,你说的是FormFile,属于struts1
人家都说了struts2了,File没有getInputStream()方法
ruiqinzhen 2010-04-27
  • 打赏
  • 举报
回复
好,谢谢了。 我试试看
hq1305018 2010-04-20
  • 打赏
  • 举报
回复
Struts的File,有一个getInputStream()方法,可以读取文件中的字节.
循环读取全部字节保存到数组中就可以了.
jack_liu4Ye 2010-04-20
  • 打赏
  • 举报
回复
我用的是commons-fileupload-1.2.1.jar插件
public void FileUpload(HttpServletRequest request, HttpServletResponse response, String uuid)
throws Exception {
Connection conn = null;
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(ConstantFactory.getConstant("HSRDB"));
conn = ds.getConnection();
try {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
FileItem item = null;
while (iter.hasNext()) {
item = (FileItem) iter.next();
if (!item.isFormField()) {
AttachmentInfo attachmentInfo = new AttachmentInfo();
String fileName = item.getName();
String shortFileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
attachmentInfo.setFileName(shortFileName);
attachmentInfo.setBizDataUuid(uuid);
InputStream stream = item.getInputStream();
byte[] bytes = new byte[1024 * 1024];
int leng = stream.read(bytes);
if (leng != -1) {
byte[] bytes1 = new byte[leng];
for (int i = 0; i < leng; i++) {
bytes1[i] = bytes[i];
}
CommonMethod.createInstance(attachmentInfo);
PreparedStatement pstmt = conn
.prepareStatement("UPDATE AttachmentInfo SET imgData = ? where AttachmentInfo.uuid = '"
+ attachmentInfo.getUuid() + "'");
pstmt.setBytes(1, bytes1);
pstmt.executeUpdate();
if (pstmt != null) {
pstmt.close();
}
}
}
}
}
catch (Exception e) {
System.out.println(e.getStackTrace());
}
finally {
if (conn != null) {
conn.close();
}
}
}


81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧