简体   繁体   English

如何在OpenStack Object Storage(Swift)中上传照片和其他文件

[英]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. 我正在制作一个Android应用程序,并尝试使用其API将文件(例如docx,音乐,照片,视频)存储在OpenStack对象存储(Swift)中。但是在存储这些文件时遇到了问题。 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. 从我得到的API中,它仅存储文件名,但是当我尝试从仪表板下载文件时,对象本身丢失了。

The API I got from OpenStack Documentations is this. 我从OpenStack文档获得的API就是这个。

Method: PUT Link: (mylink)/v1/AUTH_(account)/(container)/(object) 方法: PUT 链接: (mylink)/ v1 / AUTH_(帐户)/(容器)/(对象)

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 HEADER内容类型:(必需)X-Auth-令牌:(必需)Content-Length:(可选)ETag :(可选)Content-Disposition:(可选)Content-Encoding:(可选)X-Delete-At:(可选)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. 我尝试上传的第一个文件是照片,我尝试将其发送为binary(base64),因为API中的base也仅接受字符串。 I'm not sure where to put it, so I tried pushing it in Content-Disposition but it failed. 我不确定在哪里放置它,因此我尝试将其放入Content-Disposition中,但失败了。 I'm not sure where else can i put the photo on the limited data that can be accepted by openstack. 我不确定我还能在哪里将照片放到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. 在您的代码中,您将content-disposition指定为文件路径。

Try to make specify file object there. 尝试在那里指定文件对象。 That is you read file from file path and set content-disposition with fileReadObject. 也就是说,您从文件路径读取文件,并使用fileReadObject设置content-disposition。

Note: I am python guy. 注意:我是python家伙。 If you wish I can explain with python code. 如果您愿意,我可以用python代码进行解释。

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 要更多访问https://github.com/stacksync/android

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Springboot 上传文件和下载文件到 LINODE 对象存储? - How to Upload files and download files to LINODE object storage using Springboot? 如何使用Jclouds从OpenStack Swift获取多部分对象 - How to get a multi part object from openstack swift using jclouds OpenStack Swift多部分上传jclouds - OpenStack Swift Multi Part Upload jclouds 如何在 Java 中将图像/文件上传到 Firebase 存储? - How To upload Images/Files to Firebase storage in Java? 如何在Eclipse上使用Java Liberty将图像文件上传到Bluemix中的对象存储? - How to upload image files to Object Storage in Bluemix using Java Liberty on Eclipse? 使用Java API在Openstack Swift中复制文件时如何指定可选参数 - How can I specify optional parameters when copy files in Openstack Swift using Java API 如何将(非安卓)java 应用程序连接到 firebase 存储和上传文件? - How to conect a (non android) java app to firebase Storage and upload files? 如何将 Flux java object 上传到 Azure Blob 存储? - How to upload a Flux java object into Azure Blob Storage? 如何通过 Android 中的 web sockets (Socket.IO) 发送照片、视频和其他文件? - How to send photos,videos and other files via web sockets (Socket.IO) in Android? 如何在Openstack4j中列出超过10000个swift对象? - How to list more than 10000 swift objects in Openstack4j?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM