springMVC实现文件上传

一、配置bean

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8" />
        <property name="maxUploadSize" value="10485760000" />
        <property name="maxInMemorySize" value="40960" />
    </bean>

除此之外,需要依赖两个包:

 

二、jsp文件代码

注意,

1、一定要用 post 方法,不能使用get;

2、file需要与后端对应

见后端代码;

 

三、后端代码

 

后端方法2,推荐使用,方法传输速度很快

 

可粘贴代码

 

 

/*支持GET/POST*/
    @RequestMapping("/upload")
    public String addUser(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println("fileName---->" + file.getOriginalFilename());
        if (!file.isEmpty()) {
            try {
                FileOutputStream os = new FileOutputStream("G:/" + new Date().getTime() + file.getOriginalFilename());
                InputStream in = file.getInputStream();
                int b = 0;
                while ((b = in.read()) != -1) {
                    os.write(b);
                }
                os.flush();
                os.close();
                in.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        return "success";
    }
    
    // 第二种上传文件的方法,推荐
    @RequestMapping("/upload2")
    public String upload2(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            // 判断是否有文件
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)(request);
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file != null) {
                    String fileName = "demoUpload" + file.getOriginalFilename();
                    String path = "G:/" + fileName;
                    File localFile = new File(path);
                    file.transferTo(localFile);
                }    
            }
        }
        
        return "success";
    }
    

文件上传 <input type="file"> 这个标签自带的文件上传缺乏文件格式校验等,建议使用别的文件上传客户端控件

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值