【问题标题】:File upload using ajax and rest web service使用 ajax 和 REST Web 服务上传文件
【发布时间】:2014-08-22 09:07:06
【问题描述】:

我正在使用 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 和服务方法中应该有什么数据类型?如何在服务中获取上传的文件?任何帮助将不胜感激。

【问题讨论】:

    标签: jquery ajax web-services rest


    【解决方案1】:

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

    HTML

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

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

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

    【讨论】:

      【解决方案2】:

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

      我建议使用像jQuery File Upload 这样的jQuery 插件,或者使用Dropzone,非常棒。

      【讨论】:

        【解决方案3】:

        我是这样工作的:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-06-17
          • 1970-01-01
          • 1970-01-01
          • 2014-07-17
          • 1970-01-01
          • 1970-01-01
          • 2012-05-25
          • 1970-01-01
          相关资源
          最近更新 更多