文件上传

1. 配置上传页面

  <form action="${pageContext.request.contextPath}/file.action" enctype="multipart/form-data">

    <table align="center" border="1" width="45%">

      <tr>

        <td colspan="2" align="center">文件上传</td>

      </tr>

      <tr>

        <td>商品图片:</td>

        <td><input name="photo" type="file"/></td>

      </tr>

      <tr>

        <td colspan="2" align="center"><input type="submit" value="提交"/></td>

      </tr>

    </table>

 

2. 解析上传文件

@Controller
public class FileController {
    
    //转向文件长传页面
    @RequestMapping("/toFile.action")
    public String toFile(){
        return "file";
    }
    
    
    @RequestMapping("/file.action")
    public String updloadFile(MultipartFile photo,Model model) throws IOException{
        
        //简单方式
        FileUtils.writeByteArrayToFile
        (new File("D:\\图片样例\\"+photo.getOriginalFilename()), photo.getBytes());
        
        
        model.addAttribute("msg", "文件上传成功");
        //return "forward:/toFile.action";
        return "redirect:/toFile.action";
    }
}

3. 配置文件上传解析器

 <!--配置文件上传解析器  id的名称必须为:multipartResolver-->
       <bean id="multipartResolver"
       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
               <property name="maxUploadSize" value="10485760"></property>
       </bean>

    

posted @ 2017-07-02 20:50  Gerald_X  阅读(93)  评论(0编辑  收藏  举报