发布:从angularjs发送帖子请求时发出400个错误请求

时间:2016-04-14 17:26:08

标签: javascript angularjs spring spring-mvc

我正在编写一个用于上传文件前端的程序是angularjs,后端是spring mvc,当我选择文件并单击提交时我将收到400帖子(错误请求)

var myApp = angular.module('myApp', []);


 myApp.directive('fileModel', ['$parse', function ($parse) {
        return {
           restrict: 'A',
           link: function(scope, element, attrs) {
              var model = $parse(attrs.fileModel);
              var modelSetter = model.assign;

              element.bind('change', function(){
                 scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                 });
              });
           }
        };
     }]);

myApp.service('multipartForm', ['$http', function ($http) {
        this.post = function(uploadUrl,data){
           for (var key in data)
           var fd = new FormData();
           fd.append(key, data[key]);

           $http.post(uploadUrl, fd, {
              transformRequest: angular.identity,
              headers: {'Content-Type': undefined}
           })
           .success(function(){

           console.log("Uploaded successfully!");
           })
           .error(function(){
            console.log("error while uploading");
           });
        }  

     }]);



myApp.controller('myCtrl', ['$scope', 'multipartForm', function($scope, multipartForm){

        $scope.Submit = function(){
            var file=$scope.myFile;
            console.log("file is "+file);
           var uploadUrl = "uploads";
           multipartForm.post(uploadUrl,file);
        }


     }]);

和服务器端的Controller代码是

 @RestController
 public class FileController {

@RequestMapping(value="uploads", method=RequestMethod.POST)
public ModelAndView handleFileUpload(@ModelAttribute Document document,@RequestParam("file") MultipartFile file,
        HttpServletRequest request,HttpServletResponse response) throws IOException{

    System.out.println("in the file Controller");
    //ServletContext context = request.getServletContext();
    byte[] fileBytes = null;
    FileInputStream inputStream = null;
    ServletOutputStream outStream = null;
    BufferedOutputStream stream = null;
    ModelAndView model = new ModelAndView("helloword");
    String myfile = file.getOriginalFilename();

    String message = "the file is with server "+myfile;

    fileBytes = file.getBytes();
    model.addObject("message",message);

    String rootpath = System.getProperty("catalina.home");
    File dir = new File(rootpath +File.separator + "tmpFiles");
    if(!dir.exists()){
        dir.mkdirs();
    }
    System.out.println(dir);
    File serrverFile = new File(dir.getAbsolutePath() + File.separator + "download");
    stream = new BufferedOutputStream(new FileOutputStream(serrverFile));
    stream.write(fileBytes);

    stream.close();
/*  String serverFileName = serrverFile.getAbsolutePath();

    System.out.println(serverFileName);
    File fileDownload = new File(serverFileName);
    try {
        inputStream = new FileInputStream(fileDownload);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }*/

    /*String mimeType = context.getMimeType(serverFileName);
    if(mimeType == null){
        mimeType = "application/octet-stream"; 
    }
    response.setContentType(mimeType);
    response.setContentLength(file.getSize());

    String headerKey = "Content-Deposition";
    String headerValue = String.format("attachment; filename=\"%s\"",file.getName());
    response.setHeader(headerKey, headerValue);

    try {
        outStream = response.getOutputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }

    byte[] buffer = new byte[1000000000];
    int bytesRead = -1;

    try {
        while((bytesRead = inputStream.read(buffer))!= -1){
            outStream.write(buffer, 0 , bytesRead);

        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        inputStream.close();
        outStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    */

    return model;
}

如果我使用jsp页面而不是angularjs然后它工作正常,但我需要它在anjularjs。所以我在这里错过了一些东西。请让我知道

0 个答案:

没有答案