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

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();


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值