Spring Ajax文件上传无法查找功能

时间:2016-11-25 15:25:37

标签: javascript angularjs ajax spring

我在Chrome上遇到此错误。当调用使用Angular和Ajax将文件上传到Spring MVC时,它无法找到该函数。

  

未捕获的ReferenceError:未定义uploadFile(...)

<form id="upload-file-form">
    <label for="upload-file-input">Upload your file:</label>
    <input id="upload-file-input" type="file" name="uploadfile" accept="*" />
    <button value="Submit" onclick="uploadFile()" >Upload</button>
</form>

<script type="text/javascript">
  // bind the on-change event
  $(document).ready(function() {
  $("#upload-file-input").on("change", uploadFile);
});

/**
 * Upload the file sending it via Ajax at the Spring Boot server.
 */
function uploadFile() {
  $.ajax({
    url: "/uploadFile",
    type: "POST",
    data: new FormData($("#upload-file-form")[0]),
    enctype: 'multipart/form-data',
    processData: false,
    contentType: false,
    cache: false,
    success: function () {
      // Handle upload success
      // ...
    },
    error: function () {
      // Handle upload error
      // ...
    }
  });
} // function
</script>

这是我在Spring上的控制器

@Controller
public class uploadFile {


// The Environment object will be used to read parameters from the
// application.properties configuration file

//@Autowired
//private Environment env;

/**
 * Show the index page containing the form for uploading a file.
 */
@RequestMapping("/")
public String index() {
    return "index.html";
}

/**
 * POST /uploadFile -> receive and locally save a file.
 *
 * @param uploadfile The uploaded file as Multipart file parameter in the
 * HTTP request. The RequestParam name must be the same of the attribute
 * "name" in the input tag with type file.
 *
 * @return An http OK status in case of success, an http 4xx status in case
 * of errors.
 */
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
        @RequestParam("uploadfile") MultipartFile uploadfile) {

    try {
        // Get the filename and build the local file path
        String filename = uploadfile.getOriginalFilename();
        String filepath = Paths.get("/src/main/resources", filename).toString();

        // Save the file locally
        BufferedOutputStream stream =
                new BufferedOutputStream(new FileOutputStream(new File(filepath)));
        stream.write(uploadfile.getBytes());
        stream.close();
    }
    catch (Exception e) {
        System.out.println(e.getMessage());
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    return new ResponseEntity<>(HttpStatus.OK);
} // method uploadFile

} // class MainController

0 个答案:

没有答案