繁体   English   中英

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

[英]File upload using ajax and rest web service

我正在使用ajax和rest web服务将文件上传到服务器。 我已经捕获了文件上传事件,并在我的jquery方法中获取了文件对象。 我必须将文件对象发送到Web服务,以便我可以将文件保存到db。 这是我的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);
            }
        });
     }

我也尝试过使用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);
            }

        });

这是我的服务中的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());
}   
}

如果我直接发送文件对象而不使用formData,我得到“媒体类型不支持错误”,如果我发送formData到服务,我只获得临时文件。 ajax和服务方法中应该有什么数据类型? 如何在服务中获取上传的文件? 任何帮助将不胜感激。

我今天踩到了这个问题,我解决了这个问题:

HTML

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

阿贾克斯/ 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

@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();
    }
}

我知道有点晚了,但我看到这个问题还没有答案。

上传文件的方法与ajax请求完全不同。 此外,很难考虑所有旧浏览器。 幸运的是,其他人已经为我们解决了这个问题。

我建议像jQuery文件上传一样使用jQuery插件,或者使用Dropzone ,这非常棒。

我这样工作:

//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