使用Angularjs的$ http.post和Jersey-Rest-Backend上传文件

时间:2015-05-19 10:13:44

标签: angularjs http post jersey content-disposition

我从上传的文件中获取conent-disposition信息时遇到问题。文件上传本身工作正常。但Content-Disposition为null,这就是为什么我不知道上传文件的名称和类型。我通过angularJs的$ http服务触发帖子。

@Path("/myrest")
@Service
public class RestService<Repsonse> {

    private static final String SERVER_UPLOAD_LOCATION_FOLDER = "C://Users/steven/Desktop/upload/";


    /**
     * Upload a File
     */
    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
            @FormDataParam("myForm") InputStream fileInputStream,
            @FormDataParam("myForm") FormDataContentDisposition fileDetail
            ) {


        if (fileDetail == null) {
            System.out.println("form contentDispositionHeader is null");
//          return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(Response.Status.INTERNAL_SERVER_ERROR.toString()).build();
        } else {
            System.out.println("form: " + fileDetail.toString());
        }


        Random randomno = new Random();


//      String filePath = SERVER_UPLOAD_LOCATION_FOLDER + contentDispositionHeader.getFileName();
//      String filePath = SERVER_UPLOAD_LOCATION_FOLDER + "bla.png";
        String filePath = SERVER_UPLOAD_LOCATION_FOLDER + "test" + randomno.nextInt(10000)  + ".jpg";


        // save the file to the server
        saveFile(fileInputStream, filePath);

        String output = "File saved to server location : " + filePath;

        return Response.status(200).entity(output).build();


    }

    // save uploaded file to a defined location on the server
    private void saveFile(InputStream uploadedInputStream,
            String serverLocation) {

        OutputStream outpuStream = null;

        try {
            outpuStream = new FileOutputStream(new File(serverLocation));
            int read = 0;
            byte[] bytes = new byte[1024];

            outpuStream = new FileOutputStream(new File(serverLocation));
            while ((read = uploadedInputStream.read(bytes)) != -1) {
                outpuStream.write(bytes, 0, read);
            }

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

            try {

                if(outpuStream != null) {
                    uploadedInputStream.close();    
                }
                if(outpuStream != null) {
                    outpuStream.flush();
                    outpuStream.close();    
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

angularJs部分:

JS:

var file = $scope.myFile;

that.uploadFileToUrl = function(file, uploadUrl){

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

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

html部分:

<div ng-controller="fileUploadController">
input type="file" file-model="myFile"/>

<br>
<br>

Name: {{myFile.name}} <br>
Size: {{myFile.size}} <br>
Type: {{myFile.type}} <br>


<br>
<br>

<button ng-click="uploadFile();">Upload</button>
</div>

1 个答案:

答案 0 :(得分:1)

使用ajax上传文件是XHR 2级规范,并非所有浏览器都支持...

首选像$ .fileUpload(https://blueimp.github.io/jQuery-File-Upload/)这样的方法,用于在角度/单页应用程序中发送文件。

如果您确实知道自己要做什么,只需在FormData对象的另一个字段中添加file.name或file.fileName,然后以服务器端的方式获取它。