码迷,mamicode.com
首页 > 编程语言 > 详细

基于spring的文件上传--单文件上传

时间:2016-06-10 23:15:07      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

Spring配置文件

    <bean id="multipartResolver"
            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="2000000"/>
    </bean>

jsp页面

<form:form commandName="product" action="product_save" method="post" enctype="multipart/form-data">
    <fieldset>
        <legend>Add a product</legend>
        <p>
            <label for="name">Product Name: </label>
            <form:input id="name" path="name" cssErrorClass="error"/>
            <form:errors path="name" cssClass="error"/>
        </p>
        <p>
            <label for="description">Description: </label>
            <form:input id="description" path="description"/>
        </p>
        <p>
            <label for="price">Price: </label>
            <form:input id="price" path="price" cssErrorClass="error"/>
        </p>
        <p>
            <label for="image">Product Image: </label>
            <input type="file" name="images[0]"/>
        </p>
        <p id="buttons">
            <input id="reset" type="reset" tabindex="4">
            <input id="submit" type="submit" tabindex="5" 
                value="Add Product">
        </p>
    </fieldset>
</form:form>

controller层,第一个方法是跳转到页面,第二个方法是提交表单的方法。这中做法,即使在表单页面中加入multiple在页面中可以选择多个文件,但是在后台接收的时候也只能接收一个,(我这边测试的结果是接收了多个文件中的最后一个)

    @RequestMapping(value = "/product_input")
    public String inputProduct(Model model) {
        model.addAttribute("product", new Product());
        return "ProductForm";
    }

    @RequestMapping(value = "/product_save")
    public String saveProduct(HttpServletRequest servletRequest,
            @ModelAttribute Product product, BindingResult bindingResult,
            Model model) {

        List<MultipartFile> files = product.getImages();

        List<String> fileNames = new ArrayList<String>();

        if (null != files && files.size() > 0) {
            for (MultipartFile multipartFile : files) {

                String fileName = multipartFile.getOriginalFilename();
                fileNames.add(fileName);

                File imageFile = new File(servletRequest.getServletContext()
                        .getRealPath("/image"), fileName);
                try {
                    multipartFile.transferTo(imageFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // save product here
        model.addAttribute("product", product);
        return "ProductDetails";
    }

 参考资料:spring MVC 学习指南

基于spring的文件上传--单文件上传

标签:

原文地址:http://www.cnblogs.com/rocky-AGE-24/p/5574409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!