SpringMVC 的文件上传和文件下载

近期复习整理文件的上传下载流程。

主要流程:

1、在pom.xml文件中添加实现文件上传和下载的依赖。

		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.3</version>
		</dependency>
2、在Springmvc-config.xml文件中,添加支持文件上传的类,具体代码如下:
<bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760"></property>
        <property name="defaultEncoding" value="utf-8"></property>
    </bean>



其中id 必须要有,<property>有以下几种,按需设置就可以了:

一、文件的上传

1、文件上传的<form>表单:

<form action="/admin/register" method="post" enctype="multipart/form-data">
 <label>头像</label>
 <input type="file" name="userHeader">
<label>账户:</label>
 <input type="text" name="account" id="account">
<label>密码:</label>
 <input type="password" name="password" id="password">
 <label>生日:</label>
 <input type="Date" name="birthday" id="birthday">
 <label>性别</label>
 <input  name ="sex" type="radio" value="男">男<input  name ="sex" type="radio" value="女">女
<label>邮箱:</label>
 <input type="text" name="email" id="email">
<button   type="submit" id="tijiao" >提交</button>




需要注意的就是必须添加enctype="multipart/form-data"

input 的类型是file。

2、上传文件controller的写法。

 @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@Validated User user ,Errors errors,@RequestParam("userHeader") MultipartFile userHeader,
                           Model model, HttpServletRequest request,
                           HttpServletResponse response
    ) {
        if (errors.hasErrors()) {
            for (ObjectError objectError : errors.getAllErrors()) {
                System.out.print(objectError.getDefaultMessage());
            }
            model.addAttribute("error", errors.getAllErrors().get(0).getDefaultMessage());
            return "register";
        }
        if (userHeader != null && !userHeader.isEmpty()) {
            String filePath = request.getServletContext().getRealPath("/image");
            String fileName = userHeader.getOriginalFilename();
            File file = new File(filePath + File.separator + fileName);//此时文件还在temp文件里
            try {
                userHeader.transferTo(file);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        user.setId(userList.size() + 1);
        userList.add(user);
        return "redirect:/login";

    }



 
  
 

重点在if条件语句那一段,

if (userHeader != null && !userHeader.isEmpty()) {
    //获取你要存放图片的位置,需要在工程中新建一个image文件来存放图片。
    String filePath = request.getServletContext().getRealPath("/image");
    //获取到图片的名字
    String fileName = userHeader.getOriginalFilename();
    //创建一个目标路径和名字相同的文件
    File file = new File(filePath + File.separator + fileName);//此时文件还在temp文件里
    try {
        //将文件从临时文件夹中传到服务器的指定文件中。
        userHeader.transferTo(file);
    } catch (Exception e) {
        e.printStackTrace();
    }

}
错误记录:
1、在上传的过程中,出现过400错误,400错误一般指的是请求数据的格式不对,通常情况下就是form表单的name
和pojo类中的
名字不对应,我的错误就是@validate这个注解和Errors分开了,
 
 
@Validated User user ,Errors errors,这两个一定连在一起,否则一定会报错。
2、image文件一定要建对地方,在target目录下也要新建一个image文件。目录结构如下,

二、文件的下载

文件下载controller写法如下:

不理解@pathVariable可自行百度,该controller暂时只是实现在url输入 图片地址并下载,具体完善以后在补充,

@RequestMapping(value = "/downLoad/{imagename}/{type}" )
    public  ResponseEntity<byte[]> downLoad(@PathVariable String imagename,
                                            @PathVariable String type,
            HttpServletRequest request) throws  Exception{
//获取到服务器中image文件的地址
 String filepath = request.getServletContext().getRealPath("/image/");
//因为url不会识别“.”这个字符,所以自动加上
 String fileFullName = imagename+"."+type;

 File newFile = new File(filepath+File.separator+fileFullName);
        HttpHeaders httpHeaders =  new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment",fileFullName, Charset.forName("utf-8"));//防止中文乱码
 
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    return  new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(newFile),httpHeaders, HttpStatus.CREATED);
    }
}

欲完善,待补充。



猜你喜欢

转载自blog.csdn.net/chuyuyin/article/details/80786520