简体   繁体   English

使用ajax和rest web服务上传文件

[英]File upload using ajax and rest web service

I am using ajax and rest web service to upload files to the server. 我正在使用ajax和rest web服务将文件上传到服务器。 I have captured the file upload event and got the file object in my jquery method. 我已经捕获了文件上传事件,并在我的jquery方法中获取了文件对象。 I have to send the file object to web service so that i can save the file to db. 我必须将文件对象发送到Web服务,以便我可以将文件保存到db。 Here is my jquery code.. 这是我的jquery代码..

  $scope.selectFile = function (fileObj) {
     if(fileObj!=undefined){
        $.ajax({
            url : "/RestServices/services/uploadFile",
            type : "POST",
            data : fileObj,
            processData: false,
            contentType: false,
            success : function(result) {
                $scope.$apply();
            },
            error : function(xhr, tStatus, err) {
                // alert(err);
            }
        });
     }

I have tried using FormData also, but I couldn't get the file in web service. 我也尝试过使用FormData,但我无法在Web服务中获取该文件。

    var formData = new FormData(); 
    formData.append("fileToUpload", fileObj);   

     if(fileObj!=undefined){
        $.ajax({
            url : "/RestServices/services/uploadFile",
            type : "POST",
            data : formData,
            processData: false,
            contentType: false,
            success : function(result) {
                $scope.$apply();
            },
            error : function(xhr, tStatus, err) {
                // alert(err);
            }

        });

Here is my java code in service 这是我的服务中的java代码

@POST
@Path("/uploadFile")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void uploadFile(File formData) {     
try {
        System.out.println(formData.getFileName());             
   } catch (Exception e) {
    LOGGER.error("Exception in Upload File Endpoint"+ e.getMessage());
}   
}

If I send file Object directly without using formData, i am getting "media type not supported error" and if i send formData to service, i am getting temporary file only. 如果我直接发送文件对象而不使用formData,我得到“媒体类型不支持错误”,如果我发送formData到服务,我只获得临时文件。 What datatype should be there in ajax and in service methods? ajax和服务方法中应该有什么数据类型? How can I get the uploaded file in the service? 如何在服务中获取上传的文件? Any help will be appreciated. 任何帮助将不胜感激。

I stepped upon this problem today, and I solved it like this: 我今天踩到了这个问题,我解决了这个问题:

HTML HTML

 <input type="button" value="Upload document" class="btn btn-xs btn-primary uploadDocumentOnboarding">
 <input id="file" type="file" class="findDocumentOnboarding">

Ajax/Jquery 阿贾克斯/ jQuery的

$(".uploadDocumentGeneral").on("click", function (evt) {

var documentData = new FormData();
documentData.append('file', $('input#file.findDocumentOnboarding')[0].files[0]);
$.ajax({
    url: url,
    type: 'POST',
    data: documentData,
    cache: false,
    contentType: false,
    processData: false,
    success: function (response) {
        alert("Document uploaded successfully.");
    }
});

return false;

}); });

JAVA JAVA

@POST
@Path("upload/{id}")
@Consumes({"application/x-www-form-urlencoded", "multipart/form-data"})

public void addBlob(@PathParam("id") Integer id, @FormDataParam("file") InputStream uploadedInputStream) throws IOException {
    E24ClientTemp entityToMerge = find(id);
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int read = 0;
        byte[] bytes = new byte[1024];
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        entityToMerge.setTestBlob(out.toByteArray());
        super.edit(entityToMerge);
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}

I know it's a little late but I saw the question didn't have an answer yet. 我知道有点晚了,但我看到这个问题还没有答案。

The method of uploading a file is really different than just an ajax request. 上传文件的方法与ajax请求完全不同。 Additionally, it is really hard to consider all the old browsers. 此外,很难考虑所有旧浏览器。 Fortunately, other people have solved this problem for us. 幸运的是,其他人已经为我们解决了这个问题。

I recommend using a plugin for jQuery like jQuery File Upload , or use Dropzone , which is totally awesome. 我建议像jQuery文件上传一样使用jQuery插件,或者使用Dropzone ,这非常棒。

I have it working this way: 我这样工作:

//JAVASCRIPT

    var objFile = $jQuery("#fileToUpload");
    var file = objFile[0].files[0];
    API.call({
        url : "rest-url/upload",
        type : "POST",
        contentType : "multipart/form-data",
        data: file,
        processData: false
    }); 

//JAVA

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("rest-url/upload")
public Response upload(InputStream fileInputStream) throws Exception {
    //here you got your file
    return Response.ok().entity(new Object("response")).build();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM