简体   繁体   中英

How to upload photos and other files in OpenStack Object Storage(Swift)

I'm making an Android Application and trying to store files, eg docx, music, photos, videos in OpenStack object storage(Swift) using it's API.But I'm having a problem in storing these files. From the API that I got, it only stores the name of the file but the object itself is missing when i try to download it from the dashboard.

The API I got from OpenStack Documentations is this.

Method: PUT Link: (mylink)/v1/AUTH_(account)/(container)/(object)

HEADER Content-type: (required) X-Auth-Token: (required) Content-Length: (optional) ETag:(optional) Content-Disposition: (optional) Content-Encoding: (optional) X-Delete-At: (optional) X-Object-Meta-PIN: X-Delete-After: X-Object-Meta

BODY None

The first file that I tried to upload is a photo, I tried sending it as binary(base64) because base also in the API it only accepts strings. I'm not sure where to put it, so I tried pushing it in Content-Disposition but it failed. I'm not sure where else can i put the photo on the limited data that can be accepted by openstack.

Please help. I want to view the file that I have uploaded from phone and download it from dashboard.

This is my code:

        HttpClient httpclient = new DefaultHttpClient();
        HttpPut httpost = new HttpPut("mylink/v1/AUTH_fa6362c6520449f9a8905e84fee68f8c/photos/"+imagename);
        try {   
              httpost.setHeader("X-Auth-Token", "nasbfdblfdfsdfsdfd123a");              
              httpost.setHeader("Content-Type", "application/octet-stream");    
              httpost.setHeader("Content-Length ", Integer.toString(binaryimagelength) );   
              httpost.setHeader("Content-Disposition ",  binaryimage);// this is path of the image from the phone memory (e.g. )    

             Log.i("", "pushing your data");    

             HttpResponse response=httpclient.execute(httpost);
             ResponseHandler<String> responseHandler = new BasicResponseHandler();
             String response2 = httpclient.execute(httpost, responseHandler);
             Log.i("", "Response1:   " + response.getStatusLine());
             Log.i("", "Response2:   " + response2);


        }catch (IOException e) {                    
            Log.e("", "IOException " + e.toString());
            // TODO Auto-generated catch block

            AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this,AlertDialog.THEME_DEVICE_DEFAULT_LIGHT).create();
             alertDialog.setTitle("Error");
             alertDialog.setMessage(e.toString());
             alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                   // TODO Add your code for the button here.

                }
             });
             alertDialog.show();
        } 

In your code, You specified content-disposition as file path.

Try to make specify file object there. That is you read file from file path and set content-disposition with fileReadObject.

Note: I am python guy. If you wish I can explain with python code.

Put it in the request body.

Something like:

httpost.setEntity(new FileEntity(new File(binaryimage)));

I saw your question, and you inspired me to do my own code, so here it is, I hope it works for you

public int uploadToSwift(String filePath, String container) {
    File file = new File(filePath);
    String fileName = file.getName();
    long binaryLength = file.length();
    int statusCode;

    // Start http communications
    HttpClient httpclient = HttpClientBuilder.create().build();
    System.out.println("Communicating to: http://"+IP+"/v1/AUTH_e3fb300a1a1d48d49fb6512658eaebf5/"+container+"/"+fileName);
    HttpPut httpost = new HttpPut("http://"+IP+":8080/v1/AUTH_e3fb300a1a1d48d49fb6512658eaebf5/"+container+"/"+fileName);
    try {   
          httpost.setHeader("X-Auth-Token", openStackToken);              
          httpost.setHeader("Content-Type", "application/octet-stream");    
          httpost.setHeader("Content-Length ", Long.toString(binaryLength) );
          httpost.setEntity(new FileEntity(file));
         System.out.println("Sending your data: " + fileName);    

         HttpResponse response = httpclient.execute(httpost);
         statusCode = response.getStatusLine().getStatusCode();
         // A file was placed on the container
         if(statusCode == 201){
             System.out.println(response.getStatusLine());
             Header[] headers = response.getAllHeaders();
             for(Header header : headers)
                 System.out.println(header.getName() + " " + header.getValue());
         } else {
             System.out.println(response.getStatusLine());
         }

    }catch (IOException e) {                    
        System.out.println("IOException " + e.toString());
        return 500;
    } 
    return statusCode;
}

you can upload file by this code

public void uploadFileSmart(MyAsyncTask<Object, Integer, Boolean> task, Uri selectedFile, String parentId)
        throws IOException, NoInternetConnectionException, NotLoggedInException, UnexpectedStatusCodeException,
        FileNotFoundException, UnauthorizedException {

    if (!Utils.isNetworkConnected(context)) {
        throw new NoInternetConnectionException();
    }

    if (!isLoggedin) {
        throw new NotLoggedInException();
    }

    InputStream fis = context.getContentResolver().openInputStream(selectedFile);

    // TODO: do get filename and filesize in a functions.
    String fileName = "";
    long fileSize = 0;
    String scheme = selectedFile.getScheme();
    if (scheme.equals("file")) {
        File file = new File(selectedFile.getPath());
        fileName = file.getName();
        fileSize = file.length();
    } else if (scheme.equals("content")) {

        String[] proj = {"_data"};
        Cursor cursor = context.getContentResolver().query(selectedFile, proj, null, null, null);
        if (cursor.moveToFirst()) {
            File file = new File(cursor.getString(0));
            fileName = file.getName();
            fileSize = file.length();
        } else {
            throw new IOException("Can't retrieve path from uri: " + selectedFile.toString());
        }
    }

    /*
    if (fileName.length() == 0 || fileSize == 0) {
        throw new IOException("File name is empty or file size is 0.");
    }
    */

    String path = "/stacksync/files";
    List<Pair<String, String>> params = new ArrayList<Pair<String, String>>();
    params.add(new Pair<String, String>("file_name", fileName));
    params.add(new Pair<String, String>("overwrite", Boolean.TRUE.toString()));

    if (parentId != null) {
        params.add(new Pair<String, String>("parent", parentId));
    }

    String urlString = Utils.buildUrl(storageURL, path, params);

    URL url = new URL(urlString);

    long startTime = System.currentTimeMillis();
    Log.i(TAG, "Uploading file: " + urlString);

    // Open a connection to that URL.
    HttpsURLConnection ucon = (HttpsURLConnection) url.openConnection();

    ucon.setRequestMethod("PUT");
    ucon.addRequestProperty(FilesConstants.X_AUTH_TOKEN, authToken);
    ucon.addRequestProperty(FilesConstants.STACKSYNC_API, "True");

    // this timeout affects how long it takes for the app to realize
    // there's a connection problem
    ucon.setReadTimeout(connectionTimeout);

    ucon.setDoOutput(true);

    ucon.connect();

    OutputStream os = ucon.getOutputStream();

    BufferedInputStream bfis = new BufferedInputStream(fis);
    byte[] buffer = new byte[1024];
    int len;
    int total = 0;
    int lastUpdated = 0;
    int percent = 0;

    while ((len = bfis.read(buffer)) > 0) {
        total += len;
        percent = (int) (total * 100 / fileSize);
        if (lastUpdated != percent) {
            task.setProgress(percent);
            lastUpdated = percent;
        }

        os.write(buffer, 0, len);
    }

    task.setProgress(100);

    // clean up
    os.flush();
    os.close();
    bfis.close();

    int statusCode = ucon.getResponseCode();

    if (statusCode >= 200 && statusCode < 300) {
        Log.i(TAG, "upload completed in " + ((System.currentTimeMillis() - startTime) / 1000) + " sec");

    } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        isLoggedin = false;
        throw new UnauthorizedException();
    } else {
        Log.e(TAG, "Unexpected status code: " + statusCode);
        throw new UnexpectedStatusCodeException("Status code: " + statusCode);
    }
}

to more visit https://github.com/stacksync/android library

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM