如何通过java服务在azure目录中添加文件?

时间:2017-05-10 13:35:55

标签: java spring api azure

我正在创建应用程序,我希望将文件夹从本地存储(从PC)存储到在任何azure共享下创建的目录。我在azure的存储帐户的“文件”下工作。

这是我的代码:

@Override
    public String uploadDirectory(JSONObject jsonInput) throws IOException {
        CloudFileClient fileClient = null;
        try{
        fileClient = FileClientProvider.getFileClientReference();
        String directoryLocation = jsonInput.get("directoryLocation").toString();
        File f = new File(directoryLocation);
        listFilesForFolder(f);

        CloudFileShare share = fileClient.getShareReference(f.getName().toLowerCase().replace(".", "").replace("_", ""));
        if (share.createIfNotExists()) {
            System.out.println("New share created");
        }
        CloudFileDirectory rootDir = share.getRootDirectoryReference();
        CloudFileDirectory sampleDir = rootDir.getDirectoryReference(f.getName().toLowerCase().replace(".", "").replace("_", ""));
        if (sampleDir.createIfNotExists()) {
            System.out.println("new directory created");
        } 
        for ( ListFileItem fileItem : rootDir.listFilesAndDirectories() ) {
            System.out.println(fileItem.getUri());
        }

        }catch(Exception e)
        {
            System.out.println("Exception "+e);
        }
        return "Check";
    } 

如何将所有文件夹'f'及其内容存储到目录'sampleDir'?

1 个答案:

答案 0 :(得分:2)

您可以使用以下示例代码将本地文件夹及其内容上传到应用程序中的Azure文件存储。

@Override
public String uploadDirectory(JSONObject jsonInput) throws IOException {
    CloudFileClient fileClient = null;
    try {
        fileClient = FileClientProvider.getFileClientReference();
        String directoryLocation = jsonInput.get("directoryLocation").toString();
        File f = new File(directoryLocation);

        CloudFileShare share = 
        fileClient.getShareReference(f.getName().toLowerCase().replace(".", "").replace("_", ""));
        if (share.createIfNotExists()) {
            System.out.println("New share created");
        }
        CloudFileDirectory rootDir = share.getRootDirectoryReference();

        listFilesAndUploadToCloud(f.getAbsolutePath(), rootDir);

    } catch(Exception e) {
        System.out.println("Exception " + e);
    }
    return "Check";
} 

public void listFilesAndUploadToCloud(String filePath, CloudFileDirectory storageDir) throws Exception {

    File f = new File(filePath);
    ArrayList<File> files = new ArrayList<File>(Arrays.asList(f.listFiles()));

    for (File file : files) {
        if (file.isFile()) {
            CloudFile cloudFile = storageDir.getFileReference(file.getName());
            cloudFile.uploadFromFile(file.getAbsolutePath());
        } else {
            CloudFileDirectory cloudDir = storageDir.getDirectoryReference(file.getName());
            if (cloudDir.createIfNotExists()) {
                listFilesAndUploadToCloud(file.getAbsolutePath(), cloudDir);
            }
        }
    }

}