Spring MVC使用Ajax上传多个文件

时间:2014-03-11 06:16:43

标签: ajax spring spring-mvc

<body>    
    <form id="form1" modelAttribute="uploadForm" enctype="multipart/form-data">  
        <label for="sampleText">Please enter a text </label>
        <input id="sampleText" name="sampleText" type="text" /> <br/>
,   
        <label for="sampleFile">Please select a file</label>
        <input id="sampleFile" name="files[0]" type="file" style="border: solid 1px black" /> <br/>

        <label for="sampleFile1">Please select a file</label>
        <input id="sampleFile1" name="files[1]" type="file" style="border: solid 1px black" /> <br/>

        <input id="uploadBtn" type="button" value="Ajax Submit" onClick="Checkfiles();"></input>
    </form>

    <script type="text/javascript">
    function Checkfiles()
    {
    var fup = document.getElementById('sampleFile');
    var fileName = fup.value;
    var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
    if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "doc" || ext == "txt")
    {
        performAjaxSubmit();
    } 
    else
    {
    alert("Upload Gif or Jpg images only");
    fup.focus();
    return false;
    }
    }
        function performAjaxSubmit() {
            var sampleText = document.getElementById("sampleText").value;
            var sampleFile = document.getElementById("sampleFile").files[0];
            var sampleFile1= document.getElementById("sampleFile1").files[1];
            var formdata = new FormData();

            formdata.append("files[0]", sampleFile);                    
            formdata.append("files[1]", sampleFile1);
            var xhr = new XMLHttpRequest();
            xhr.open("POST","save.html", true);
            xhr.send(formdata);
            xhr.send(formdata);

            }

    </script>       

在控制器端

@RequestMapping( value = "/save", method = RequestMethod.POST )
public String save( @ModelAttribute( "uploadForm" ) FileUploadForm uploadForm,
        BindingResult result,
        Model map ) throws IllegalStateException, IOException
{

    List<MultipartFile> files = uploadForm.getFiles();

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

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

            }
            InputStream inputStream = null;
            inputStream = multipartFile.getInputStream();
            if( multipartFile.getSize() > 10000 )
            {
                System.out.println( "File Size exceeded:::" + multipartFile.getSize() );

            }
            String fileName = multipartFile.getOriginalFilename();
            fileNames.add( fileName );
            System.out.println( fileName );
            //Handle file content - multipartFile.getInputStream()
            File dest = new File( "C:/Aslam/files/" + fileName );
            multipartFile.transferTo( dest );
        }
    }
    System.out.println( "save.html is called" );
    map.addAttribute( "files",
                      fileNames );

    return "file_upload_success";
}

要求是在没有提交表单的情况下使用带弹簧的ajax,但上面代码中的问题是文件[1]没有保存, 我不确定发生了什么 - xhr没有将文件[1]传递给控制器​​或控制器没有读取文件[1]

请有人帮助我,我是ajax的新手

1 个答案:

答案 0 :(得分:0)

以下代码使用Apache文件上传工作..

在Javascript中

var fd = new FormData();
fd.append('file',packageFile);
fd.append('file',xmlFile);

var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);

xhr.onreadystatechange = function() { });

xhr.send(fd);

在Spring控制器中

public String save(HttpServletRequest request, HttpServletResponse httpServletResponse) {

    boolean isMultipart;
    String response = null;
    String myFileName = null;                
    String filename = null;

    isMultipart = ServletFileUpload.isMultipartContent(request);

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List fileItems = upload.parseRequest(request);

        Iterator i = fileItems.iterator();
        while (i.hasNext()) {

        FileItem fi = (FileItem) i.next();

        if (!fi.isFormField()) {

            InputStream in = fi.getInputStream();

            filename = UPLOAD_FILE_DIR + sessionId + "/" + fi.getName();

            if (filename.endsWith(".zip")) {
                myFileName = fi.getName();

            } else if(filename.endsWith(".xml")) {
                myFileName = fi.getName();                              
            }

            File fd = new File(UPLOAD_FILE_DIR + sessionId + "/" + myFileName);

            final File parent_directory = fd.getParentFile();

            FileOutputStream fos = new FileOutputStream(fd);

            byte[] buffer = new byte[4096];

            int length;while ((length = in.read(buffer)) > 0) {

               fos.write(buffer, 0, length);

            }
            fos.close();
       }
 }

编辑:以下是获取所选文件并将其添加到FormData

的Javascript代码
packageFile = $.find(".fileselector")[0].files[0];
xmlFile = $.find(".fileselector")[1].files[0];

var fd = new FormData();
fd.append('file',packageFile);
fd.append('file',xmlFile);

以下是我的XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);

xhr.onreadystatechange = function() { });

xhr.send(fd);

以下是用于上传文件的HTML标记

<input id="upf_local_fileinput1" type="file" name="myFile" path="fileData" class="fileselector">                            
<input id="upf_local_fileinput2" type="file" name="myFile" path="fileData" class="fileselector">

如果您仍然遇到问题,请尝试使用以下代码,因为我记得在某些版本的Spring中,上述代码无效。

MultipartHttpServletRequest multi = (MultipartHttpServletRequest) request;

Map fileMap = multi.getFileMap();

Iterator fileIt = fileMap.keySet().iterator();
while (fileIt.hasNext()) {
   String fileKey = (String) fileIt.next();
   MultipartFile file = (MultipartFile) fileMap.get(fileKey);
   if (file != null) {
      bufReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
   } else {
      System.out.println("Invalid file");
   }


   String str;
   File file = new File(imeiFilePath);
   FileWriter fw = new FileWriter(file);
   BufferedWriter bw = new BufferedWriter(fw);

   while ((str = bufReader.readLine()) != null) {
      if (bw != null) {
          bw.write(str);
          bw.newLine();
      }
   }
   if (bw != null) {
      bw.flush();
      bw.close();
   }
}