0

Um so basically I'm trying to upload a file from my android phone to app script which will create the file in google drive. This works will when accessing via browser. But when trying to do a multipart/httppost/formdata, it doesn't work. the params AFAIK seems to be correct. Posting Strings work without any issue (tried with volley library), however files/images don't seem to work. Adding Google drive SDK is not an option for me since most of my app users are going to be using custom custom OS, hence google play services not working correctly. Current code for app script

server.gs

function doGet(e) {
 return HtmlService.createHtmlOutputFromFile('form.html');

}

function uploadFiles(form) {

try {

var dir = "Files";
var folder, folders = DriveApp.getFoldersByName(dir);

if (folders.hasNext()) {
  folder = folders.next();
} else {
  folder = DriveApp.createFolder(dir);
}

var blob = form.myFile;    

  // var file = folder.createFile("BlobTest","test");   

var file = folder.createFile(blob);    
file.setDescription("Uploaded by " + form.myName);

return file.getId() ;

 } catch (error) {

return error.toString();
  }

}




**Form.html**




<form id="myForm">
<input type="text" name="myName" placeholder="name..">
<input type="file" name="myFile" >
<input type="submit" value="Upload File" 
       onclick="this.value='Uploading..';
                google.script.run.withSuccessHandler(fileUploaded)
                .uploadFiles(this.parentNode);
                return false;">
</form>

<div id="output"></div>

<script>
function fileUploaded(status) {
    document.getElementById('myForm').style.display = 'none';
    document.getElementById('output').innerHTML = status;
}
</script>

<style>
input { display:block; margin: 20px; }
</style>





 **And my android code**





private class uploadimg extends AsyncTask<Void, Integer, Integer> {


    int serverResponseCode = 0;


    String serverResponseMessage;

    @Override
    protected void onPreExecute() {






        super.onPreExecute();
    }




    @Override
    protected Integer doInBackground(Void... params) {
        return uploadFilez();
    }



    public int uploadFilez() {





        String  sourceFileUri   =   selectedImagePath;



        String upLoadServerUri = url;


        String fileName = sourceFileUri;



        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);
        if (!sourceFile.isFile()) {

            return 0;
        }
        try { // open a URL connection to the Servlet



            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);
            conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("myFile", fileName);
           // conn.setRequestProperty("Accept-Charset", "UTF-8");
            //    String k ="";


            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name="+"tits"+";filename=\""+ fileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);


            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }



            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            serverResponseMessage = conn.getResponseMessage();






            if(serverResponseCode == 200){
                runOnUiThread(new Runnable() {
                    public void run() {





                    }
                });
            }

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();


        } catch (MalformedURLException ex) {

            ex.printStackTrace();

        } catch (Exception e) {

            e.printStackTrace();

        }
        dialog.dismiss();
        return serverResponseCode;
    }




    @Override
    protected void onPostExecute(Integer result) {


        super.onPostExecute(result);
    }

}

any help is appreciated :) thank you

Assassin Shadow
  • 61
  • 1
  • 2
  • 9

0 Answers0