开发者

spring 3 upload many files

yeah,our customer want to upload more than one file. we use spring 3 mvc. the official example like this:

markup:

<form method="post" action="/form" enctype="multipart/form-data">
    <input type="text" name="name"/>
    <input type="file" name="file"/>
    <input type="submit"/>
</form>

code:

@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 so开发者_运维问答mewhere
        return "redirect:uploadSuccess";
    } else {
        return "redirect:uploadFailure";
    }
}

there is only one file,so i can write the file input name in the method. but what should i do if i want to upload many files. i could not write all the file input names because if is generated by the js code. i only know that its name like 'attach_' then ,what should i write in the method ? if i write like this

@RequestParam() MultipartFile file

or

@RequestParam("attach_") MultipartFile file

i'll get a error.


A much simpler way - works for me

/*** Upload Images ***/
@RequestMapping(value = "/images/upload", method = RequestMethod.POST)
public void upload(@RequestParam("file") List<MultipartFile> files, @RequestParam("user") String user) {

    files.forEach((file -> System.out.println(file.getOriginalFilename())));

}


I have it working with Spring 3.0.4 (there was an issue in previous versions of Spring, so be sure to use >= 3.0.4).

To test it, you can use the following steps:

public class MultiPartFileUploadBean {

    private List<MultipartFile> files;

    public void setFiles(List<MultipartFile> files) {
        this.files = files;
    }

    public List<MultipartFile> getFiles() {
        return files;
    }
}

The controller:

@RequestMapping(value = "/uploadtest", method = RequestMethod.POST)
public String uploadtestProcess(MultiPartFileUploadBean file, BindingResult bindingResult,
        Model model) throws IOException {
    ... // binding check
    StringBuilder sb = new StringBuilder();
    List<MultipartFile> files = file.getFiles();
    for(MultipartFile f:files)
        sb.append(String.format("File: %s, contains: %s<br/>\n",f.getOriginalFilename(),new String(f.getBytes())));
    String content = sb.toString();
    model.addAttribute("content", content);
    return "uploadtest";
}

The jsp:

<form method="post" action="/uploadtest" enctype="multipart/form-data">
<p>Type: <input type="text" name="type" value="multiPartFileSingle" size="60" /></p>
<p>File 1: <input type="file" name="files[0]" size="60" /></p>
<p>File 2: <input type="file" name="files[1]" size="60" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
<c:if test="${not empty content}">
<p>The content uploaded: <br/>${content}</p>


I found clearer to use the MultipartHttpServletRequest object as a parameter to the controller method:

@RequestMapping(value = "/save", method=RequestMethod.POST)
protected String save(Model model, MultipartHttpServletRequest multipartRequest) {
    MultipartFile file = multipartRequest.getFile("field-name");
    // Also multiple files with same name
    List<MultipartFile> files = multipartRequest.getFiles("multifield-name");
    // ...
}

Link to the docs: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-multipart-resolver-commons


You use model and form.

( Html / Jsp )

<form id="uploadForm" method="POST"enctype="multipart/form-data/charset=UTF-8">
     //...multi file, add dynamic input
     <input type="file" name="file"/>
     <input type="file" name="file"/>
     <input type="file" name="file"/>
     <input type="file" name="file"/>
</form>
<input type="button" id="save_button" value="save" />

(Js)

var form = new FormData(document
        .getElementById('uploadForm'));

$.ajax({
    url : "/test/upload/file,
    type : 'POST',
    dataType : 'text',
    data : form,

    processData : false,
    contentType : false,

    success : function(response) {
        if (response == "success") {
            document.location.reload(true);

        } else {
            $("#editMsg").text("fail");
        }
    },
    error : function(request, status, error) {

    }
});

( Model )

public class fileModel {
   private List<MultipartFile> file; // this name = input name

  ... setter, getter
}

( Controller )

@RequestMapping(value = "/upload/file", method = RequestMethod.POST)
public @ResponseBody String uploadFiles(fileModel model, HttpServletRequest req) {

    return "success" // <-- debug. break point !! Your watch model. 
}


You can find it here:

http://dhruba.name/2008/12/27/implementing-single-and-multiple-file-multipart-uploads-using-spring-25/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜