Upload File to Quickbooks online with IDS V3

2019-06-13 22:21发布

问题:

I would like to upload a file to QuickBooks Online using IDS V3. I followed the steps described here https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/020_key_concepts/attachments. Here is my source code

 URL url = new URL("https://quickbooks.api.intuit.com/v3/company/My_company_ID/upload");
    HttpURLConnection request = (HttpURLConnection) url.openConnection();
    request.setDoOutput(true);
    request.setRequestMethod("POST");
    HttpParameters para = new HttpParameters();
    //String status = URLEncoder.encode("中 文","utf-8").replaceAll("\\+", "%20");
    //para.put("status", status);
    String boundary = "---------------------------37531613912423";
    //String content = "--"+boundary+"\r\nContent-Disposition: form-data; name=\"status\"\r\n\r\n";
    String pic = "\r\n--"+boundary+"\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"postpic.gif\"\r\nContent-Type: image/gif\r\n\r\n";
    byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();  
    File f = new File("/Users/cnanfack/Documents/oml_map1.gif");
    FileInputStream stream = new FileInputStream(f);
    byte[] file = new byte[(int)f.length()];
    stream.read(file);
    String lineEnd = "\r\n";
    String header =   "Content-Disposition: form-data; name=\"file_metadata_0\""+lineEnd
    +"Content-Type: application/xml; charset=UTF-8"+lineEnd
    +"Content-Transfer-Encoding: 8bit"+lineEnd;

   String attachable =  header+"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Attachable xmlns=\"http://schema.intuit.com/finance/v3\" domain=\"QBO\" sparse=\"false\">"
    +"<EntityRef type=\"Bill\">285</EntityRef>"
    +"<Size>4099</Size>"
    +"<ContentType>image/gif</ContentType>"
    +"<FileName>postpic.gif</FileName>"
    +"</Attachable>";

    request.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary); 
    //request.setRequestProperty("Content-Length", String.valueOf(boundary.getBytes().length+"test".getBytes().length+pic.getBytes().length+f.length()+end_data.length)); 
    //consumer.setAdditionalParameters(para);
      consumer.sign(request);
      OutputStream ot = request.getOutputStream();
      ot.write(end_data);
      ot.write(attachable.getBytes());
      ot.write(end_data);
      //ot.write(status.getBytes());
      ot.write(pic.getBytes());
      ot.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
      ot.write(file);
      ot.write(end_data);
      ot.flush();
      ot.close();
    System.err.println("Sending request...");
    request.connect();
    System.err.println("Response: " + request.getResponseCode() + " "
          + request.getResponseMessage());
    BufferedReader reader =new BufferedReader(new InputStreamReader(request.getInputStream()));
    String b = null;
    while((b = reader.readLine())!=null){
       System.err.println(b);
    }

The returned result:

Response: 200 OK
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2013-11-10T20:24:27.823-08:00"/>

But I don't see the file on Quickbooks Online. Maybe I miss something. Can someone help me? Thank you in advance

回答1:

I had tried this Upload endpoint call using Java Devkit. It is working fine. PFB details.

 -  Request URI : https://quickbooks.api.intuit.com/v3/company/688779980/upload? Http
 -  Method : POST Content-Disposition: form-data; name="file_metadata_2bddf" 
 -  Content-Type: application/xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Attachable xmlns="http://schema.intuit.com/finance/v3">
    <FileName>images.jpg</FileName>
    <ContentType>image/jpeg</ContentType>
    <Lat>25.293112341223</Lat>
    <Long>-21.3253249834</Long>
    <PlaceName>Fake Place</PlaceName>
    <Note>Attachable note 900a49e1</Note>
    <Tag>Attachable tag 900a49e1</Tag>
</Attachable>

Response XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2013-11-12T05:58:25.296-08:00">
    <AttachableResponse>
        <Attachable domain="QBO" sparse="false">
            <Id>100000000000543524</Id>
            <SyncToken>0</SyncToken>
            <MetaData>
                <CreateTime>2013-11-12T05:58:26-08:00</CreateTime>
                <LastUpdatedTime>2013-11-12T05:58:26-08:00</LastUpdatedTime>
            </MetaData>
            <FileName>images.jpg</FileName>
            <FileAccessUri>/v3/company/688779980/download/100000000000543524</FileAccessUri>
            <TempDownloadUri>https://intuit-qbo-prod-19.s3.amazonaws.com/688779980%2Fattachments%2Fimages-1384264705362.jpg?Expires=1384265606&amp;AWSAccessKeyId=AKIAJEXDXKNYCBUNCCCQ&amp;Signature=ESZPzeO%2B5YWxw8VOWMVMBRnvIdw%3D</TempDownloadUri>
            <Size>58616</Size>
            <ContentType>image/jpeg</ContentType>
            <Lat>25.293112341223</Lat>
            <Long>-21.3253249834</Long>
            <PlaceName>Fake Place</PlaceName>
            <Note>Attachable note 8219e79a</Note>
            <Tag>Attachable tag 8219e79a</Tag>
            <ThumbnailFileAccessUri>/v3/company/688779980/attachable-thumbnail/100000000000543524</ThumbnailFileAccessUri>
        </Attachable>
    </AttachableResponse>
</IntuitResponse>

From the ThumnailFileAccessUri property I got the following attachment URI which I had used for Download endpoint.

/v3/company/688779980/attachable-thumbnail/100000000000543524

Download Endpoint(GET)-

https://quickbooks.api.intuit.com/v3/company/688779980/download/100000000000543521

JAVA/.Net SDK download link - https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits

Hope it will be useful.

EDIT- Adding Java code snippet

public static void executeUploadForImageFilePoc(DataService service) throws ParseException, FMSException, FileNotFoundException {
    System.out.println("executeUploadForImageFile");
    String uuid = UUID.randomUUID().toString().substring(0, 8);
    Attachable attachable1 = new Attachable();
    //attachable.setSize(new Long("34234"));
    attachable1.setLat("25.293112341223");
    attachable1.setLong("-21.3253249834");
    attachable1.setPlaceName("Fake Place");
    attachable1.setNote("Attachable note " + uuid);
    attachable1.setTag("Attachable tag " + uuid);
    Attachable attachable = attachable1;
    attachable.setFileName("images.jpg");
    attachable.setContentType("image/jpeg");
    File file = new File("C:\\images_new.jpg");
    InputStream in = new FileInputStream(file);

    //Upload endpoint call
    Attachable attachableOutput = service.upload(attachable, in);

    //Check return XML
    attachable.getFileAccessUri();
    System.out.println(attachableOutput.getFileAccessUri());
    System.out.println(attachableOutput.getFileName());

    //Download endpoint call
    InputStream output = service.download(attachableOutput);
    try {
        BufferedImage bImageFromConvert = ImageIO.read(output);

        ImageIO.write(bImageFromConvert, "jpg", new File("C:\\images_new_manas.jpg"));

    } catch (IOException e) {
        throw new FMSException("Error while reading the upload file.", e);
    }
}

Thanks



回答2:

I have a working code in dotnet. See if it works for you:

DataService.DataService commonServiceQBO= new DataService.DataService(qboContextoAuth);
      string imagePath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "\\", "Services\\Resource\\image.jpg");
                        System.IO.FileInfo file = new System.IO.FileInfo(imagePath);
                        Attachable attachable = new Attachable();
                        attachable.AttachableRef = new AttachableRef[1];
                        attachable.AttachableRef[0].EntityRef = new ReferenceType();
                        attachable.AttachableRef[0].EntityRef.type = "Bill";
                        attachable.AttachableRef[0].EntityRef.Value = "12";
                        attachable.Lat = "25.293112341223";
                        attachable.Long = "-21.3253249834";
                        attachable.PlaceName = "Fake Place";
                        attachable.Note = "Attachable note123 ";
                        attachable.Tag = "Attachable tag123 ";
                        using (System.IO.FileStream fs = file.OpenRead())
                                {
                                    attachable.ContentType = "image/jpeg";
                                    attachable.FileName = file.Name;
                                    Attachable attachableUploaded = commonServiceQBO.Upload(attachable, fs);
                                }

For download use: byte[] responseByte = service.Download(attachableUploaded);