簡體   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