第十一章 文件上传-跟赵大笨笨学SpringMVC

来源:互联网 发布:iframe 端口不同 跨域 编辑:程序博客网 时间:2024/05/22 23:58

直接看代码如何实现:

jsp

为了能上传文件,jsp要满足三个要求。
1.必须将表单的method设置为post。
2.必须将表单的enctype设置为multipart/form-data。
3.有一个type为file的input标签。

<form:form commandName="productAddBean" action="produceAdd" method="post" enctype="multipart/form-data">     <div class="form-group" >        <label for="firstname" class="col-sm-2 control-label">产品编号</label>        <div class="col-sm-10">            <form:input type="text" style='margin-bottom: 20px;' class="form-control" path="productId" placeholder="请输入产品编号"/>        </div>     </div>     <form:errors path="productId"/>     <br/>     <div class="form-group" >         <label for="firstname" class="col-sm-2 control-label">产品名称</label>         <div class="col-sm-10">               <form:input type="text" style='margin-bottom: 20px;' class="form-control" path="productName" placeholder="请输入产品名称"/>          </div>     </div>     <form:errors path="productName"/>     <br/>     <div class="form-group" >         <label for="firstname" class="col-sm-2 control-label">产品图片</label>         <div class="col-sm-10">             <form:input type="file" style='margin-bottom: 20px;' class="form-control" path="file"/>         </div>      </div>      <br/>      <div class="col-sm-5"></div>       <div class="col-sm-7">           <button type="submit" class="btn btn-default">追加</button>      </div></form:form>

这里写图片描述

model

    // 产品编号    @NotEmpty(message="产品编号不能为空")    private String productId;    // 产品名称    @NotEmpty(message="产品名称不能为空")    private String productName;    // 产品图片    private MultipartFile file;    public String getProductId() {        return productId;    }    public void setProductId(String productId) {        this.productId = productId;    }    public String getProductName() {        return productName;    }    public void setProductName(String productName) {        this.productName = productName;    }    public MultipartFile getFile() {        return file;    }    public void setFile(MultipartFile file) {        this.file = file;    }

注意为MultipartFile类型。

Controller

 @RequestMapping("/produceAdd")    public String produceAdd(@Valid ProductAddBean bean, BindingResult result,Model model) {        if (result.hasErrors()){            return "produce_add";        }        MultipartFile file = bean.getFile();        // 判断上传的文件是否为空。        if (!file.isEmpty()) {            // 上传之后存放的路径。            String path = "F:\\upload";            // 获取文件名            String filename = file.getOriginalFilename();            // 上传            try {                file.transferTo(new File(path + File.separator + filename));            } catch (IllegalStateException | IOException e) {            }        }        model.addAttribute("productAddBean", bean);        return "produce_add_confirm";    }

配置文件:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

我们 上传一个1.txt
这里写图片描述
去d盘下面找找
这里写图片描述

原创粉丝点击