使用Ajax上传一个表单中的数据和文件以休息Web服务?

时间:2016-03-21 10:33:48

标签: jquery ajax rest

您好我正在尝试使用jquery ajax上传文件来休息网络服务。

HTML:

<form id="myFormID" method="post" enctype="multipart/form-data">
    <input name="image" type="file" />
    <input type="button" id="myId" />
</form>

Jquery ajax代码是。

$('#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();
    }
}

我的应用程序中出现内部服务器错误:

  

javax.servlet.ServletException:Servlet.init()

0 个答案:

没有答案