您的位置:首页 > 数据库

文件上传以及导入二进制到数据库程序心得

2013-12-26 09:32 696 查看
2013-12-26 08:49:22 frank

写文件上传以及导入到数据库程序心得

----------------------------------

项目采用的框架是:

Spring MVC

上传功能的实现:

step1,在配置文件中加上下面的配置

<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name='maxUploadSize'>
<!--限制最大文件是10M-->
<value>100010485761</value>
</property>
</bean>


step2,在请求处理方法里通过

// 将request转换成MultipartHttpServletRequest
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile mfile = multipartRequest.getFile("file"); // 获得文件
InputStream input = mfile.getInputStream(); // 获得输入流


step3,通过流将文件重新写出来

// 存放文件的目录
File dir = new File(proPath + "/WEB-INF/madecarddata");
if (dir.exists()) {
dir.mkdir();
}
// 生成文件的路径
File file = new File(dir + "/" + filename);
System.out.println(file.getName());
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
byte[] bbs = new byte[1024];
int len = -1;
while ((len = in.read(bbs)) != -1) {
fos.write(bbs, 0, len);
}
in.close();
fos.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("生成文件失败");
return false;
} catch (IOException e) {
e.printStackTrace();
System.out.println("生成文件失败");
return false;
}


解析文件时遇到的问题 :

//1.乱码问题
String encoding = "GBK";
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
//或者
str = bufferedReader.readLine();
st = new String(str.getBytes(),"GBK");

//2.上传二进制文件到数据库
//首先要关闭自动提交
session.connection().setAutoCommit(false);
//在return前手动提交
session.connection().commit();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐