Jquery 使用Ajax到rest web服务以一种形式上载数据和文件?

Jquery 使用Ajax到rest web服务以一种形式上载数据和文件?,jquery,ajax,rest,Jquery,Ajax,Rest,您好,我正在尝试使用jQueryAjax将文件上传到RESTWeb服务 HTML: web服务代码是 @POST @Path("/uploadfile") @Consumes(MediaType.MULTIPART_FORM_DATA) public String uploadFile( @FormDataParam("file") InputStream fileInputString, @FormDataParam("file") FormDataContentDisposi

您好,我正在尝试使用jQueryAjax将文件上传到RESTWeb服务

HTML:

web服务代码是

@POST
@Path("/uploadfile")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(
    @FormDataParam("file") InputStream fileInputString,
    @FormDataParam("file") FormDataContentDisposition fileInputDetails) {

    saveToDisk(fileInputString , fileInputDetails);
    return "File Uploaded Sucessfully!!!";
}

public void saveToDisk(
    InputStream fileInputString,
    FormDataContentDisposition fileInputDetails) {

    String uploadedFileLocation="d://upload/image";
    try {
        OutputStream out = new FileOutputStream(new  File(uploadedFileLocation));
        byte[] bytes = new byte[1024];
        int read = 0;
        while ((read = fileInputString.read(bytes)) != -1) {
            out.write(bytes, 0, read);       
        }
        out.flush();  
        out.close();                

    } catch (IOException ex) {

        ex.printStackTrace();
    }
}
我的应用程序中出现内部服务器错误:

javax.servlet.ServletException:servlet.init()


你不能像那样通过ajax上传文件。例如,使用FileReader对象将图像发布为base64并在服务器端对其进行解码。[
$('#myId').click(function() {
    var formData = new FormData($(this)[0]);
    $.ajax({
        url : 'url',
        dataType : "json",
        type : "POST",
        contentType : 'application/json; charset=utf-8',
        data :formData  ,
        async : true,
        processData : false,
        cache : false,
        success : function(data) {                  

        },
        error : function(xhr) {
            alert('error');
        }
    });
});
@POST
@Path("/uploadfile")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(
    @FormDataParam("file") InputStream fileInputString,
    @FormDataParam("file") FormDataContentDisposition fileInputDetails) {

    saveToDisk(fileInputString , fileInputDetails);
    return "File Uploaded Sucessfully!!!";
}

public void saveToDisk(
    InputStream fileInputString,
    FormDataContentDisposition fileInputDetails) {

    String uploadedFileLocation="d://upload/image";
    try {
        OutputStream out = new FileOutputStream(new  File(uploadedFileLocation));
        byte[] bytes = new byte[1024];
        int read = 0;
        while ((read = fileInputString.read(bytes)) != -1) {
            out.write(bytes, 0, read);       
        }
        out.flush();  
        out.close();                

    } catch (IOException ex) {

        ex.printStackTrace();
    }
}