使用Ajax Request将文件上传到Spring MVC Controller

时间:2014-07-17 12:07:07

标签: ajax spring jsp spring-mvc

我想使用Ajax请求将文件从jsp页面上传到控制器,我不知道哪里出错但我的代码没有向控制器发送请求。

JSP:

  function FileUploadRequest()
        {
            var fd = new FormData();
            fd.append("FileUpload", document.getElementById('FileUpload').files[0]);

             alert(fd);
             $.ajax({  
                    type :"Get",   
                    url : "fileUploadInfo.html",   
                   data:fd,
                    //data:fd ? fd : form.serialize(),

                    success : function(response) {  
                    alert(response); 
                   //document.getElementById("FileUploadForm").reset();
                  }   
                 });
        }
        </script>
    <form id="FileUploadForm"  enctype="multipart/form-data">
      <table width="100%" border="0" cellspacing="5" cellpadding="0">
       <tr>
                <td align="left" valign="middle">Config File</td>
                <td align="left" valign="middle"><input type="file" id="FileUpload"></td>
              </tr>
              <tr>
        <td align="left" valign="middle">&nbsp;
        </td>
        <td align="left" valign="middle">
        <input type="reset" name="button" id="button" value="Clear">&nbsp;
        <input type="button" name="button" id="button" value="Submit" onclick="FileUploadValidation();"></td>
      </tr>
      </table>
      </form>

控制器:

@RequestMapping(value ="/fileUploadInfo", method = RequestMethod.GET)

        public @ResponseBody String HelloWorld(MultipartHttpServletRequest request,
                HttpServletResponse response)
        {

             Iterator<String> itr =  request.getFileNames();

             MultipartFile mpf = request.getFile(itr.next());
             System.out.println(mpf.getOriginalFilename() +" uploaded!");
            return "Hi";


        }

1 个答案:

答案 0 :(得分:1)

你可以这样做有这样的函数,并使用ajaxForm

function ajaxUploading() {

    $("#FileUploadForm").ajaxForm({
        beforeSend: function () {
            var percentVal = '0%';

        },
        resetForm: true,
        uploadProgress: function (event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
        },
        beforeSerialize: function ($Form, options) {

           //Do anything
        },
        success: function (data, status, xhr, $form) {
             //Do anything
        }
});


}

然后在服务器端

@RequestMapping(value = "fileUploadInfo", method ={RequestMethod.GET,RequestMethod.POST})
@ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file,
            HttpServletRequest request, HttpServletResponse response,
            ) throws IOException {


        String fileName = null;


        if (null != file && !file.isEmpty()) {
            fileName = file.getOriginalFilename();



            String path = "Can be any path on disk";

            File filePath = new File(path);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }

            Utils.uploadFile(file, path, fileName);
    }
}

上传文件使用功能的实现:

public static boolean uploadFile(MultipartFile file, String path,
            String fileName) {
        boolean uploaded = false;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            inputStream = file.getInputStream();
            outputStream = new FileOutputStream(path + "/" + fileName);

            int readBytes = 0;
            byte[] buffer = new byte[100];

            while ((readBytes = inputStream.read(buffer, 0, 100)) != -1) {
                outputStream.write(buffer, 0, readBytes);
            }
            outputStream.close();
            inputStream.close();
            uploaded = true;
        } catch (Exception e) {
            e.printStackTrace();
            uploaded = false;
        }
        return uploaded;
    }