将文件插入Google云端硬盘时出现IOException

时间:2012-07-14 02:38:41

标签: google-drive-api

将图片发布到Google云端硬盘时遇到以下问题:

java.io.IOException: insufficient data written
at sun.net.www.protocol.http.HttpURLConnection$StreamingOutputStream.close(HttpURLConnection.java:2822)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:83)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:895)
at com.google.api.client.googleapis.media.MediaHttpUploader.upload(MediaHttpUploader.java:280)
at com.google.api.services.drive.Drive$Files$Insert.executeUnparsed(Drive.java:309)
at com.google.api.services.drive.Drive$Files$Insert.execute(Drive.java:331)

我认为它与此有关:http://code.google.com/p/google-api-java-client/issues/detail?id=521

有没有办法规避这个?我想知道是否可以在不使用google drive sdk的resumable upload api的情况下插入文件?

2 个答案:

答案 0 :(得分:2)

我相信我回答了自己关于如何直接上传的问题:

Insert insert = this.driveClient.files().insert(body, mediaContent);
insert.getMediaHttpUploader().setDirectUploadEnabled(true);
File result = insert.execute();

但是,仍然不确定数据写入错误的原因。

答案 1 :(得分:0)

使用setDirectUploadEnabled(false)选项,insert.execute()会在获得最小块大小之前立即开始上传第一个块。您必须完成request.getPart(“fleInputName”),然后启动驱动器上载过程。

我用阻塞线程解决了这个问题:

public class GetPartThread  extends Thread {

        private HttpServletRequest request;
        private String inputAttr;

        private Part part;



        public GetPartThread(HttpServletRequest request, String inputAttr) {
            super();
            this.request = request;
            this.inputAttr = inputAttr;
        }


        @Override
        public void run(){
                synchronized(this){
                    try {
                        part = request.getPart(inputAttr);
                        notify();

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
        }

        public Part getPart() {
            return part;
        }

        public void setPart(Part part) {
            this.part = part;
        }

然后在您的驱动器上传方法中使用它:

GetPartThread getPart = new GetPartThread(request, "templatefile");
getPart.start();
synchronized(getPart){
try{
    System.out.println("Waiting for Part upload to complete...");
    getPart.wait();
}catch(InterruptedException e){
    e.printStackTrace();
}
System.out.println("Part upload Finished...");

Part part = getPart.getPart();

//Here continue with processing your "part" and upload it to drive with the method you set for uploading to drive ... }

这应该有用。

注意:使用Drive Resumable Media Uploads时不要使用setConvert(true)这会引发异常,因为上传到驱动器的第一个块的转换开始而不是上传完成后。