springMVC上传文件(11)

结合后台框架springmvc实现文件的简单上传,主要有下面几步:
1. 在前台网页编写最简单的上传组件:(注意enctype=”multipart/form-data”一定要有)

<form name="userForm" action="/springMVC7/file/upload2" method="post" enctype="multipart/form-data" >
        选择文件:<input type="file" name="file">
        <input type="submit" value="上传" >
</form>

2.在SpringMVC-servlet.xml文件中添加下面的代码:

<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>

3.后台关键代码:

@Controller
@RequestMapping("/file")
public class UploadController {

    @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("D:/" + 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) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return "/success";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值