Using a MultipartResolver with Commons FileUpload[就是使用commons FileUpload上传文件]

来源:互联网 发布:新手护肤步骤知乎 编辑:程序博客网 时间:2024/05/01 14:16
依照文档中做的起始就是需要配置一下和倒下包就行了。

当然在我们上传文件的时候我们是使用spring 和commonsFileUpLoad的集成的文件上传解析器MultipartResolver

为什么使用它呢?其实也是为了我们 在spring中能够使用到他,因为spring其实也没有做什么,就是将这个类做了这么一步、
CommonsMultipartResolver extends CommonsFileUploadSupport
        implements MultipartResolver,ServletContextAware

看到没,其实就是做了一下spring和commonsFile的支持,继承了CommonsFileUploadSupport类
和实现ServletContextAware类

  
闲话不多说,在xml中的配置如下:
1
<bean id="multipartResolver"    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    <!-- one of the properties available; the maximum file size in bytes -->    <property name="maxUploadSize" value="100000"/>//这是 byte</bean>

2
当然就是导入我们的commons-fileupload.jar。
但是我们没这个jar的,但是幸好我用struts2,那么我们可以找到,但是我们需要导人两个,
一个是commons-fileupload-**.jar和commons-io-**.jar{**指的是版本号}


3(直接拷官方文档)

16.9.4 Handling a file upload in a form

After the MultipartResolver completes its job, the request is processed like any other. First, create a form with a file input that will allow the user to upload a form. The encoding attribute (enctype="multipart/form-data") lets the browser know how to encode the form as multipart request:

<html>    <head>        <title>Upload a file please</title>    </head>    <body>        <h1>Please upload a file</h1>        <form method="post" action="/form" enctype="multipart/form-data">            <input type="text" name="name"/>            <input type="file" name="file"/>            <input type="submit"/>        </form>    </body></html>

The next step is to create a controller that handles the file upload. This controller is very similar to a normal annotated @Controller, except that we use MultipartHttpServletRequest or MultipartFile in the method parameters:

@Controllerpublic class FileUpoadController {    @RequestMapping(value = "/form", method = RequestMethod.POST)    public String handleFormUpload(@RequestParam("name") String name,         @RequestParam("file") MultipartFile file) {        if (!file.isEmpty()) {            byte[] bytes = file.getBytes();            // store the bytes somewhere           return "redirect:uploadSuccess";       } else {           return "redirect:uploadFailure";       }    }}