表单文件上载

1.在浏览器配置表单,表单文件上载必须注意三点:

1.1必须使用post方法提交表单

1.2必须设置enctype=“mutipart/form-data”

1.3必须使用input type=“fie”元素选择文件

	<form enctype="multipart/form-data" action="user/upload.do" method="POST">
		图片:<input name="image" type="file"><br>
		说明:<input name="memo" type="text"><br>
		<input type="submit" value="Send File">
	</form>

2.添加pom.xml中添加组件

                <dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.3</version>
		</dependency>

在springmvc的配置文件中添加组件配置(spring framework3.2.8 api文档中查找)

	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- one of the properties available; the maximum file size in bytes -->
		<property name="maxUploadSize" value="100000" />
	</bean>

修改value值以适应文件大小的需求,添加对中文文件名的编码属性

	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- one of the properties available; the maximum file size in bytes -->
		<property name="maxUploadSize" value="100000" />
		<!-- 设置中文文件名的编码 -->
		<property name="defaultEncoding" value="UTF-8"></property>
	</bean>

3.在控制层添加请求对应的方法

	@RequestMapping("/upload.do")
	@ResponseBody
	public ResponseResult<Void> upload(MultipartFile image,String memo){
		//MultipartFile封装了全部的上载信息
		//利用其方法可以获取全部的上载信息
		//显示上载文件的文件名OriginalFilename
		System.out.println(image.getOriginalFilename());
		System.out.println(memo);
		//返回结果
		return new ResponseResult<Void>(1,"Success");
	}

服务器端处理关键点:

1.导入上载处理组件commons-fileupload用于解析文件上载请求

2.配置spring mvc上载解析器,使用fileupload组件

扫描二维码关注公众号,回复: 1029381 查看本文章

    --设置最大上载限制

    --设置文件名的中文编码

3.控制器中使用MultipartFile接受上载的文件数据

    --注意:变量名与客户端name属性一致

    --文件的全部信息可以通过MultipartFile对象获得

4.将上载的文件放到相应的文件中

@RequestMapping("/upload.do")
	@ResponseBody
	public ResponseResult<Void> upload(MultipartFile image,String memo,HttpServletRequest request) throws IllegalStateException, IOException{
		//MultipartFile封装了全部的上载信息
		//利用其方法可以获取全部的上载信息
		//显示上载文件的文件名OriginalFilename
		System.out.println(image.getOriginalFilename());
		//将上载的文件直接保存到一个目标文件中 image.transferTo(file);
		String filename=image.getOriginalFilename();
		//web路径
		String path="/upload";
		//将web路径转换为操作系统的实际路径
		path=request.getServletContext().getRealPath(path);
		//输出实际路径
		System.out.println(path);
		File dir=new File(path);
		dir.mkdir();
		File file=new File(path,filename);
		image.transferTo(file);
		System.out.println(memo);
		//返回结果
		return new ResponseResult<Void>(1,"Success");
	}


猜你喜欢

转载自blog.csdn.net/weixin_36552034/article/details/79377213