SpringMvc上传文件



总共分三步:

第一步:在springmvc-servlet.xml 添加如下代码:

<!--
		========================华丽的分割 文件上传==================================
	-->

	<!--id="multipartResolver" 不能随便写-->
	<!--同时在jsp页面 在form表单里面添加一个属性 enctype="multipart/form-data"	-->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!--maxUploadSize:文件上传的单位是byte为单位 比如2兆 就是2097152	-->
		<property name="maxUploadSize" value="2097152"></property>
	</bean>

第二步:Jsp页面在Form表单里面添加属性 enctype="multipart/form-data"


第三步:在Controller添加代码

// =============================以下是文件上传=========================================

	/**
	 * @throws Exception
	 * 
	 * @Title: upLoadFile
	 * @Description: 上传一个图片到upload文件夹
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 */
	@RequestMapping("/upLoadFile.do")
	public String upLoadFile(HttpServletRequest request) throws Exception {
		/**
		 * 第一步转化request
		 */
		MultipartHttpServletRequest rm = (MultipartHttpServletRequest) request;
		/**
		 * 获得文件rm.getFile("pic");参数就是jsp里面定义的file input标签的name
		 */
		CommonsMultipartFile cFile = (CommonsMultipartFile) rm.getFile("pic");
		/**
		 * 获得文件的字节数组
		 */
		byte[] b = cFile.getBytes();

		String fileName = "";
		/**
		 * 获得当前时间的最小精度 小时分钟秒 三个S代表三个随机数
		 */
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		fileName = format.format(new Date());
		/**
		 * 产生三个随机数
		 */
		Random random = new Random();
		for (int i = 0; i < 3; i++) {
			// 0-9之间做随机数
			fileName = fileName + random.nextInt(9);
		}
		/**
		 * 获得原始文件名
		 */
		String origFileName = cFile.getOriginalFilename();
		/**
		 * xxxx.jpg 拿到文件后缀名
		 */
		String suffix = origFileName.substring(origFileName.lastIndexOf("."));
		/**
		 * 拿到上传路径
		 */
		String path = request.getSession().getServletContext().getRealPath(
				"upload");
		/**
		 * 定义文件的输出流
		 */
		OutputStream out = new FileOutputStream(new File(path + "/upload"
				+ fileName + suffix));
		out.write(b);
		out.flush();
		out.close();

		return "index";
	}

	/**
	 * 
	 * @Title: toUpLoad
	 * @Description: 跳转到upLoad.jsp
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 */
	@RequestMapping("/toUpload.do")
	public String toUpLoad() {
		return "upLoad";
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值