从 Google App Engine (Java) 将文件上传到 Google 云存储

2024-02-23

如何将文件从谷歌应用程序引擎中的servlet上传到谷歌云存储?

当我这样做时,Google 云存储不知道文件的类型,即我从 HTML 表单发送的文件。编写 HTML/JavaScript 和 servlet 将文件上传到云存储的正确方法是什么?


下面是来自 Google 的代码示例,用于使用 Java 脚本与云存储进行交互。它的功能远不止上传,即您可以下载、创建新存储桶等。下面我添加了我用来上传的功能,该功能源自此示例。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset='utf-8' />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script src="https://apis.google.com/js/client.js"></script>
    <script type="text/javascript">
        /**
         * The Project ID of your Google Cloud Storage Project.
         */
        var PROJECT = 'abcd';
        /**
         * Enter a client ID for a web application from the Google Developers
         * Console on the "APIs & auth", "Credentials" page.
         * In your Developers Console project add a JavaScript origin
         * that corresponds to the domain from where you will be running the
         * script. For more info see:
         * https://developers.google.com/console/help/new/#generatingoauth2
         */
        var clientId = '701111116470-55bj2lkjlkkjkljhe97di22gus5hs3.apps.googleusercontent.com';
        /**
         * Enter the API key from the Google Developers Console, by following these
         * steps:
         * 1) Visit https://cloud.google.com/console and select your project
         * 2) Click on "APIs & auth" in the left column and then click “Credentials”
         * 3) Find section "Public API Access" and use the "API key." If sample is
         * being run on localhost then delete all "Referers" and save. Setting
         * should display "Any referer allowed." For more info see:
         * https://developers.google.com/console/help/new/#generatingdevkeys
         */
        var apiKey = 'JHJhhguy8786875hghgjbS0nYjcMY';
        /**
         * To enter one or more authentication scopes, refer to the documentation
         * for the API.
         */
        var scopes = 'https://www.googleapis.com/auth/devstorage.full_control';
        /**
         * Constants for request parameters. Fill these values in with your custom
         * information.
         */
        var API_VERSION = 'v1';
        /**
         * Enter a unique bucket name to create a new bucket. The guidelines for
         * bucket naming can be found here:
         * https://developers.google.com/storage/docs/bucketnaming
         */
        //var BUCKET = 'code-sample-bucket-' + Date.now();
        var BUCKET = 'testbucket';
        /**
         * The name of the object inserted via insertObject method.
         */
        var object = "";
        /**
         * Get this value from the Developers Console. Click on the
         * “Cloud Storage” service in the Left column and then select
         * “Project Dashboard”. Use one of the Google Cloud Storage group IDs
         * listed and combine with the prefix “group-” to get a string
         * like the example below.
         */
        var GROUP =
                'group-kjhHJKHJKH897897878jgjghg8728f21c3ff22597efbfc63ccdb8f2294d8fd2561cb9';
        /**
         * Valid values are user-userId, user-email, group-groupId, group-email,
         * allUsers, allAuthenticatedUsers
         */
        var ENTITY = 'allUsers';
        /**
         * Valid values are READER, OWNER
         */
        var ROLE = 'READER';
        /**
         * Valid values are READER, OWNER
         */
        var ROLE_OBJECT = 'READER';
        /**
         * A list of example calls to the Google Cloud Storage JavaScript client
         * library, as well as associated explanations of each call.
         */
        var listApiRequestExplanations = {
            'listBuckets': 'This API call queries the Google Cloud Storage API ' +
            'for a list of buckets in your project, and returns the result as ' +
            'a list of Google Cloud Storage buckets.',
            'listObjects': 'This API call queries the Google Cloud Storage API ' +
            'for a list of objects in your bucket, and returns the result as ' +
            'a list of Google Cloud Storage objects.',
            'listBucketsAccessControls': 'This API call queries the Google Cloud ' +
            'Storage API for the list of access control lists on buckets in your ' +
            'project and returns the result as a list of Google Cloud Storage ' +
            'Access Control Lists.',
            'listObjectsAccessControls': 'This API call queries the Google Cloud ' +
            'Storage API for the list of access control lists on objects in your ' +
            'bucket and returns the result as a list of Google Cloud Storage ' +
            'Access Control Lists.',
            'getBucket': 'This API call queries the Google Cloud Storage API ' +
            'for a bucket in your project, and returns the result as a ' +
            'Google Cloud Storage bucket.',
            'getBucketAccessControls': 'This API call queries the Google Cloud ' +
            'Storage API for the access control list on a specific bucket ' +
            'and returns the result as a Google Cloud Storage Access Control List.',
            'getObjectAccessControls': 'This API call queries the Google Cloud ' +
            'Storage API for the access control list on a specific object ' +
            'and returns the result as a Google Cloud Storage Access Control List.',
            'insertBucket': 'This API call uses the Google Cloud Storage API ' +
            'to insert a bucket into your project.',
            'insertObject': 'This API call uses the Google Cloud Storage API ' +
            'to insert an object into your bucket.',
            'insertBucketAccessControls': 'This API uses the Google Cloud ' +
            'Storage API to insert an access control list on a specific bucket ' +
            'and returns the result as a Google Cloud Storage Access Control List.',
            'insertObjectAccessControls': 'This API uses the Google Cloud ' +
            'Storage API to insert an access control list on a specific object ' +
            'and returns the result as a Google Cloud Storage Access Control List.',
            'deleteBucket': 'This API uses the Google Cloud Storage API to delete ' +
            'an empty bucket and returns an empty response to indicate success.',
            'deleteObject': 'This API uses the Google Cloud Storage API to delete ' +
            'an object and returns an empty response to indicate success.'
        };
        /**
         * Google Cloud Storage API request to retrieve the list of buckets in
         * your Google Cloud Storage project.
         */
        function listBuckets() {
            var request = gapi.client.storage.buckets.list({
                'project': PROJECT
            });
            executeRequest(request, 'listBuckets');
        }
        /**
         * Google Cloud Storage API request to retrieve the list of objects in
         * your Google Cloud Storage project.
         */
        function listObjects() {
            var request = gapi.client.storage.objects.list({
                'bucket': BUCKET
            });
            executeRequest(request, 'listObjects');
        }
        /**
         * Google Cloud Storage API request to retrieve the access control list on
         * a bucket in your Google Cloud Storage project.
         */
        function listBucketsAccessControls() {
            var request = gapi.client.storage.bucketAccessControls.list({
                'bucket': BUCKET
            });
            executeRequest(request, 'listBucketsAccessControls');
        }
        /**
         * Google Cloud Storage API request to retrieve the access control list on
         * an object in your Google Cloud Storage project.
         */
        function listObjectsAccessControls() {
            var request = gapi.client.storage.objectAccessControls.list({
                'bucket': BUCKET,
                'object': object
            });
            executeRequest(request, 'listObjectsAccessControls');
        }
        /**
         * Google Cloud Storage API request to retrieve a bucket in
         * your Google Cloud Storage project.
         */
        function getBucket() {
            var request = gapi.client.storage.buckets.get({
                'bucket': BUCKET
            });
            executeRequest(request, 'getBucket');
        }
        /**
         * Google Cloud Storage API request to retrieve a bucket's Access Control
         * List in your Google Cloud Storage project.
         */
        function getBucketAccessControls() {
            var request = gapi.client.storage.bucketAccessControls.get({
                'bucket': BUCKET,
                'entity': GROUP
            });
            executeRequest(request, 'getBucketAccessControls');
        }
        /**
         * Google Cloud Storage API request to retrieve an object's Access Control
         * List in your Google Cloud Storage project.
         */
        function getObjectAccessControls() {
            var request = gapi.client.storage.objectAccessControls.get({
                'bucket': BUCKET,
                'object': object,
                'entity': GROUP
            });
            executeRequest(request, 'getObjectAccessControls');
        }
        /**
         * Google Cloud Storage API request to insert a bucket into
         * your Google Cloud Storage project.
         */
        function insertBucket() {
            resource = {
                'name': BUCKET
            };
            var request = gapi.client.storage.buckets.insert({
                'project': PROJECT,
                'resource': resource
            });
            executeRequest(request, 'insertBucket');
        }
        /**
         * Google Cloud Storage API request to insert an object into
         * your Google Cloud Storage bucket.
         */
        function insertObject(event) {
            try{
                var fileData = event.target.files[0];
            }
            catch(e) {
                //'Insert Object' selected from the API Commands select list
                //Display insert object button and then exit function
                filePicker.style.display = 'block';
                return;
            }
            const boundary = '-------314159265358979323846';
            const delimiter = "\r\n--" + boundary + "\r\n";
            const close_delim = "\r\n--" + boundary + "--";
            var reader = new FileReader();
            reader.readAsBinaryString(fileData);
            reader.onload = function(e) {
                var contentType = fileData.type || 'application/octet-stream';
                var metadata = {
                    'name': fileData.name,
                    'mimeType': contentType
                };
                var base64Data = btoa(reader.result);
                var multipartRequestBody =
                        delimiter +
                        'Content-Type: application/json\r\n\r\n' +
                        JSON.stringify(metadata) +
                        delimiter +
                        'Content-Type: ' + contentType + '\r\n' +
                        'Content-Transfer-Encoding: base64\r\n' +
                        '\r\n' +
                        base64Data +
                        close_delim;
                //Note: gapi.client.storage.objects.insert() can only insert
                //small objects (under 64k) so to support larger file sizes
                //we're using the generic HTTP request method gapi.client.request()
                var request = gapi.client.request({
                    'path': '/upload/storage/' + API_VERSION + '/b/' + BUCKET + '/o',
                    'method': 'POST',
                    'params': {'uploadType': 'multipart'},
                    'headers': {
                        'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
                    },
                    'body': multipartRequestBody});
                //Remove the current API result entry in the main-content div
                listChildren = document.getElementById('main-content').childNodes;
                if (listChildren.length > 1) {
                    listChildren[1].parentNode.removeChild(listChildren[1]);
                }
                try{
                    //Execute the insert object request
                    executeRequest(request, 'insertObject');
                    //Store the name of the inserted object
                    object = fileData.name;
                }
                catch(e) {
                    alert('An error has occurred: ' + e.message);
                }
            }
        }
        /**
         * Google Cloud Storage API request to insert an Access Control List into
         * your Google Cloud Storage bucket.
         */
        function insertBucketAccessControls() {
            resource = {
                'entity': ENTITY,
                'role': ROLE
            };
            var request = gapi.client.storage.bucketAccessControls.insert({
                'bucket': BUCKET,
                'resource': resource
            });
            executeRequest(request, 'insertBucketAccessControls');
        }
        /**
         * Google Cloud Storage API request to insert an Access Control List into
         * your Google Cloud Storage object.
         */
        function insertObjectAccessControls() {
            resource = {
                'entity': ENTITY,
                'role': ROLE_OBJECT
            };
            var request = gapi.client.storage.objectAccessControls.insert({
                'bucket': BUCKET,
                'object': object,
                'resource': resource
            });
            executeRequest(request, 'insertObjectAccessControls');
        }
        /**
         * Google Cloud Storage API request to delete a Google Cloud Storage bucket.
         */
        function deleteBucket() {
            var request = gapi.client.storage.buckets.delete({
                'bucket': BUCKET
            });
            executeRequest(request, 'deleteBucket');
        }
        /**
         * Google Cloud Storage API request to delete a Google Cloud Storage object.
         */
        function deleteObject() {
            var request = gapi.client.storage.objects.delete({
                'bucket': BUCKET,
                'object': object
            });
            executeRequest(request, 'deleteObject');
        }
        /**
         * Removes the current API result entry in the main-content div, adds the
         * results of the entry for your function.
         * @param {string} apiRequestName The name of the example API request.
         */
        function updateApiResultEntry(apiRequestName) {
            listChildren = document.getElementById('main-content')
                    .childNodes;
            if (listChildren.length > 1) {
                listChildren[1].parentNode.removeChild(listChildren[1]);
            }
            if (apiRequestName != 'null') {
                window[apiRequestName].apply(this);
            }
        }
        /**
         * Determines which API request has been selected, and makes a call to add
         * its result entry.
         */
        function runSelectedApiRequest() {
            var curElement = document.getElementById('api-selection-options');
            var apiRequestName = curElement.options[curElement.selectedIndex].value;
            updateApiResultEntry(apiRequestName);
        }
        /**
         * Binds event listeners to handle a newly selected API request.
         */
        function addSelectionSwitchingListeners() {
            document.getElementById('api-selection-options')
                    .addEventListener('change',
                    runSelectedApiRequest, false);
        }
        /**
         * Template for getting JavaScript sample code snippets.
         * @param {string} method The name of the Google Cloud Storage request
         * @param {string} params The parameters passed to method
         */
        function getCodeSnippet(method, params) {
            var objConstruction = "// Declare your parameter object\n";
            objConstruction += "var params = {};";
            objConstruction += "\n\n";
            var param = "// Initialize your parameters \n";
            for (i in params) {
                param += "params['" + i + "'] = ";
                param += JSON.stringify(params[i], null, '\t');
                param += ";";
                param += "\n";
            }
            param += "\n";
            var methodCall = "// Make a request to the Google Cloud Storage API \n";
            methodCall += "var request = gapi.client." + method + "(params);";
            return objConstruction + param + methodCall;
        }
        /**
         * Executes your Google Cloud Storage request object and, subsequently,
         * inserts the response into the page.
         * @param {string} request A Google Cloud Storage request object issued
         *    from the Google Cloud Storage JavaScript client library.
         * @param {string} apiRequestName The name of the example API request.
         */
        function executeRequest(request, apiRequestName) {
            request.execute(function(resp) {
                console.log(resp);
                var apiRequestNode = document.createElement('div');
                apiRequestNode.id = apiRequestName;
                var apiRequestNodeHeader = document.createElement('h2');
                apiRequestNodeHeader.innerHTML = apiRequestName;
                var apiRequestExplanationNode = document.createElement('div');
                apiRequestExplanationNode.id = apiRequestName + 'RequestExplanation';
                var apiRequestExplanationNodeHeader = document.createElement('h3');
                apiRequestExplanationNodeHeader.innerHTML = 'API Request Explanation';
                apiRequestExplanationNode.appendChild(apiRequestExplanationNodeHeader);
                var apiRequestExplanationEntry = document.createElement('p');
                apiRequestExplanationEntry.innerHTML =
                        listApiRequestExplanations[apiRequestName];
                apiRequestExplanationNode.appendChild(apiRequestExplanationEntry);
                apiRequestNode.appendChild(apiRequestNodeHeader);
                apiRequestNode.appendChild(apiRequestExplanationNode);
                var apiRequestCodeSnippetNode = document.createElement('div');
                apiRequestCodeSnippetNode.id = apiRequestName + 'CodeSnippet';
                var apiRequestCodeSnippetHeader = document.createElement('h3');
                apiRequestCodeSnippetHeader.innerHTML = 'API Request Code Snippet';
                apiRequestCodeSnippetNode.appendChild(apiRequestCodeSnippetHeader);
                var apiRequestCodeSnippetEntry = document.createElement('pre');
                //If the selected API command is not 'insertObject', pass the request
                //paramaters to the getCodeSnippet method call as 'request.wc.wc.params'
                //else pass request paramaters as 'request.wc.wc'


/*                if (apiRequestName != 'insertObject') {
                    apiRequestCodeSnippetEntry.innerHTML =
                            getCodeSnippet(request.wc.wc.method, request.wc.wc.params);
                    //Selected API Command is not 'insertObject'
                    //hide insert object button
                    filePicker.style.display = 'none';
                } else {
                    apiRequestCodeSnippetEntry.innerHTML =
                            getCodeSnippet(request.wc.wc.method, request.wc.wc);
                }*/


                apiRequestCodeSnippetNode.appendChild(apiRequestCodeSnippetEntry);
                apiRequestNode.appendChild(apiRequestCodeSnippetNode);
                var apiResponseNode = document.createElement('div');
                apiResponseNode.id = apiRequestName + 'Response';
                var apiResponseHeader = document.createElement('h3');
                apiResponseHeader.innerHTML = 'API Response';
                apiResponseNode.appendChild(apiResponseHeader);
                var apiResponseEntry = document.createElement('pre');
                apiResponseEntry.innerHTML = JSON.stringify(resp, null, ' ');
                apiResponseNode.appendChild(apiResponseEntry);
                apiRequestNode.appendChild(apiResponseNode);
                var content = document.getElementById('main-content');
                content.appendChild(apiRequestNode);
            });
        }
        /**
         * Set required API keys and check authentication status.
         */
        function handleClientLoad() {
            gapi.client.setApiKey(apiKey);
            window.setTimeout(checkAuth, 1);
        }
        /**
         * Authorize Google Cloud Storage API.
         */
        function checkAuth() {
            gapi.auth.authorize({
                client_id: clientId,
                scope: scopes,
                immediate: true
            }, handleAuthResult);
        }
        /**
         * Handle authorization.
         */
        function handleAuthResult(authResult) {
            var authorizeButton = document.getElementById('authorize-button');
            if (authResult && !authResult.error) {
                authorizeButton.style.visibility = 'hidden';
                initializeApi();
                filePicker.onchange = insertObject;
            } else {
                authorizeButton.style.visibility = '';
                authorizeButton.onclick = handleAuthClick;
            }
        }
        /**
         * Handle authorization click event.
         */
        function handleAuthClick(event) {
            gapi.auth.authorize({
                client_id: clientId,
                scope: scopes,
                immediate: false
            }, handleAuthResult);
            return false;
        }
        /**
         * Load the Google Cloud Storage API.
         */
        function initializeApi() {
            gapi.client.load('storage', API_VERSION);
        }
        /**
         * Driver for sample application.
         */
        $(window)
                .bind('load', function() {
                    addSelectionSwitchingListeners();
                    handleClientLoad();
                });
    </script>
</head>
<body>
<!--Add a button for the user to click to initiate auth sequence -->
<button id="authorize-button" style="visibility: hidden">Authorize</button>
<header>
    <h1>Google Cloud Storage JavaScript Client Library Application</h1>
</header>
<label id="api-label">Try a sample API call!</label>
<select id="api-selection-options">
    <option value="null">
        Please select an example API call from the dropdown menu
    </option>
    <option value="listBuckets">
        List Buckets
    </option>
    <option value="insertBucket">
        Insert Bucket
    </option>
    <option value="getBucket">
        Get Bucket
    </option>
    <option value="getBucketAccessControls">
        Get Bucket Access Controls
    </option>
    <option value="insertBucketAccessControls">
        Insert Bucket Access Controls
    </option>
    <option value="listBucketsAccessControls">
        List Buckets Access Control List
    </option>
    <option value="insertObject">
        Insert Object
    </option>
    <option value="listObjects">
        List Objects
    </option>
    <option value="getObjectAccessControls">
        Get Object Access Controls
    </option>
    <option value="insertObjectAccessControls">
        Insert Object Access Controls
    </option>
    <option value="listObjectsAccessControls">
        List Objects Access Control List
    </option>
    <option value="deleteObject">
        Delete Object
    </option>
    <option value="deleteBucket">
        Delete Bucket
    </option>
</select>
<br/>
<input type="file" id="filePicker" style="display: none" />
<div id="main-content">
</div>
</body>
</html>

下面是上传文件的函数,完全受到上面示例的启发。请注意,它使用 JavaScript 客户端库与 Google API (gapi) 交互,这意味着您可以通过 google 帐户进行身份验证来保护上传(https://developers.google.com/api-client-library/javascript/start/start-js https://developers.google.com/api-client-library/javascript/start/start-js).

function uploadFile(fileData, bucket) {
    var boundary = '-------314159265358979323846';
    var delimiter = "\r\n--" + boundary + "\r\n";
    var close_delim = "\r\n--" + boundary + "--";
    var reader = new FileReader();
    reader.readAsBinaryString(fileData);

    reader.onload = function (e) {
        var contentType = fileData.type || 'application/octet-stream';
        var metadata = {
            'name': fileData.name,
            'mimeType': contentType
        };
        var base64Data = btoa(reader.result);
        var multipartRequestBody =
                delimiter +
                'Content-Type: application/json\r\n\r\n' +
                JSON.stringify(metadata) +
                delimiter +
                'Content-Type: ' + contentType + '\r\n' +
                'Content-Transfer-Encoding: base64\r\n' +
                '\r\n' +
                base64Data +
                close_delim;

        var request = gapi.client.request({
            'path': '/upload/storage/v1/b/' + bucket + '/o',
            'method': 'POST',
            'params': {'uploadType': 'multipart'},
            'headers': {
                'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
            },
            'body': multipartRequestBody
        });

        try {
            request.execute(function (resp) {
                if (resp.hasOwnProperty("error")) {
                    //Treat Error
                } else {
                    //Treat Success
                }
            });
        }
        catch (e) {
            //Treat Error
        }

    };

}

最后,您可以使用Cloud Storage的对象更改通知来调用App Engine中的任务。您可以传递存储桶和文件名,并处理刚刚通过 App Engine 上传的文件。https://cloud.google.com/storage/docs/object-change-notification https://cloud.google.com/storage/docs/object-change-notification

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 Google App Engine (Java) 将文件上传到 Google 云存储 的相关文章

  • 如何在createQueryBuilder中使用通配符?

    在我的存储库类中 我使用 public function getItemsByTag tag qb this gt createQueryBuilder c gt select c gt where c tags LIKE bipolar
  • 在 OpenXML 中应用数字格式

    我正在尝试使用 OpenXML 从头开始 创建 Excel 电子表格 并且一切正常 将实际值转储到实际单元格中 但现在我正在尝试将数字格式应用于列 但遇到了问题 我有styles xml看起来像这样
  • 如何在 Angular 2 中订阅 DOMContentLoaded 事件?

    我正在将 UI 主题从 Angular 1 移植到 Angular 2 在第 1 个版本中 我有 viewContentLoaded事件 我想将其重新制作为 Angular 2 我正在尝试使用 HostListener DOMContent
  • 使用 Swift 解析框架

    有人尝试过将 Parse Framework 与 swift 一起使用吗 只要添加桥接文件 您就可以使用 swift 和 Objective C 代码 这是我的查询 从 Parse 返回的 对象 数组正确地包含了我的所有数据 但该方法在将
  • 为什么 .each 在我的 Rails 视图中完成后会重复数组? [复制]

    这个问题在这里已经有答案了 在我的 Rails 视图页面中 我有以下循环 它应该循环遍历我的 tag list 数组并打印每个标签 由于某种原因 它在打印每个单独的标签后会重复该数组 例如 这个数组有两个元素 ruby python 每个方
  • NV_path_rendering替代方案[关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我刚刚观看了 Siggraph 2012 的一个非常令人印象深刻的演示 http nvidia fullviewmedia com sig
  • addEventListener keydown 不起作用

    我在互联网上找到了一些基本的 Pong 代码 并尝试添加按键 代码在这里 http cssdeck com labs ping pong game tutorial with html5 canvas and sounds http css
  • Google 地图 api 中的 infoWindow 数组

    我寻找错误 但找不到它 由于某种原因 任何谷歌地图信息窗口总是显示相同的信息 这是一个咖啡脚本代码 infowindow new google maps InfoWindow for company in companiesData mar
  • 使用 OpenLayers 动态添加自定义标记到地图

    我想让用户在地图上添加自定义标记以及每个标记的描述 任何提示 任何教程的链接都会非常有用 您可以注册一个函数来在地图上 点击 事件 当用户单击它时 会自动添加该标记 尝试这样的事情 map is your map created using
  • 使用 PowerShell 检查 AD 中是否存在组

    我想为该组创建代码来检查该组是否存在 但是 我无法开始工作 因为它成功地将用户和组的部分成员仅添加到一个组中 而不是其他组 因为我设法在活动目录中创建一个组并从 csv 中读取 这是我的代码和结果 似乎在成功添加用户并添加组成员后我总是收到
  • 新的 .NET 6 控制台模板中的 C# 函数重载不起作用

    我在尝试重载该函数时遇到错误Print object in the 新的 NET 6 C 控制台应用程序模板 https learn microsoft com en us dotnet core tutorials top level t
  • python中匹配3个或更多相同的字符

    我正在尝试使用正则表达式在字符串中查找三个或更多相同的字符 例如 你好 不匹配 噢 会的 我尝试过做类似的事情 re compile 1 3 a zA Z re compile w 1 5 但似乎都不起作用 w 1 2 是您正在寻找的正则表
  • Android 使用非公历

    我正在创建一个DatePickerDialogFragment用户将在其中选择出生日期 我想确保我可以处理非公历日期 我无法更改在我的设备上使用的日历类型 Android 是否允许用户切换日历类型 如果是的话 步骤是什么 到目前为止我还没有
  • 如何在运行时更改 UIMenu 内 UIAction 的状态?

    如何更改 UIAction 的状态 目标是切换 UIMenu 内 UIAction 旁边的状态复选标记 更改 UIAction 的state通过存储在视图控制器中的引用似乎根本不会改变状态 我错过了什么吗 View Controller i
  • PDO 返回不正确但重复的数据。密钥不在数据库中。

    我刚开始使用 pdo 语句 所以可能是一些简单的东西 我还没有在 php net 上读过 查询数据库时我收到重复的结果 Result 0 gt Array umeta id gt 31 0 gt 31 user id gt 2 1 gt 2
  • Shap - 颜色条不显示在摘要图中

    显示summary plot时 不显示颜色条 shap summary plot shap values X train 我尝试过改变plot size 当绘图较高时 会出现颜色条 但它非常小 看起来不应该 shap summary plo
  • Javascript:修改原型不会影响现有实例[重复]

    这个问题在这里已经有答案了 我创建了原型的 2 个实例 更改了原型中的函数 更改反映在两个实例中 很棒 但是 当我通过删除该函数来修改原型时 该函数对于现有实例仍然存在 function A this name cool A prototy
  • 截断段落前 100 个字符并隐藏段落的其余内容,以通过更多/更少链接显示/隐藏其余内容

    我有一个超过 500 个字符的段落 我只想获取最初的 100 个字符并隐藏其余部分 我还想在 100 个字符旁边插入 更多 链接 单击更多链接时 整个段落应显示并编辑文本 更多 到 更少 单击 更少 时 它应切换行为 段落是动态生成的 我无
  • jvm 如何以及何时何地更改 Linux 的最大打开文件值?

    在linux中 每个登录用户的每个进程的最大打开文件数有限制 如下所示 ulimit n 1024 当我学习java nio时 我想检查这个值 因为channel在Linux中也是一个文件 所以我编写了一个客户端代码来不断创建socketC
  • 如何检测文本是否可读?

    我想知道是否有一种方法可以告诉给定的文本是人类可读的 我所说的人类可读的意思是 它有一些含义 格式就像某人写的文章 或者至少是由软件翻译器生成的供人类阅读的文章 这是背景故事 最近我正在制作一个应用程序 允许用户将短文本上传到数据库 在部署

随机推荐

  • Unity 中的单例每次调用上下文(Web 请求)

    几天前 我遇到了 ASP Net 线程的问题 我希望每个网络请求都有一个单例对象 我实际上需要这个来完成我的工作单位 我想为每个 Web 请求实例化一个工作单元 以便身份映射在整个请求过程中都有效 这样我就可以使用 IoC 将我自己的 IU
  • 线性排序算法

    我是研究算法的新手 我也不是计算机科学毕业生 然而 在阅读线性排序非比较算法时 我可以理解基数排序是计数排序的扩展 我不清楚的是计数排序的局限性 当计数排序似乎可以满足我需要避免 O n logn 比较的目的时 为什么我要选择基数排序 这确
  • AWS CDK 突然失败,Construct 无法转换为 InterfaceVpcEndpoint 类

    截至昨天我的cdk代码开始返回错误 java lang ClassCastException 类 software constructs Construct 无法转换为类 software amazon awscdk services ec
  • 当尝试运行以生成报告并在 Maven 项目中发送电子邮件时,缺少必需的类:org/codehaus/gmaven/mojo/GroovyMojo

    我有 Maven JUnit 项目 它可以成功编译 构建和测试 另外 当我做mvn site所有测试均成功运行并生成surefire report target site 目录 现在 我需要将此报告通过电子邮件发送给指定的收件人 这是我的
  • Sinatra 不会在 Chrome 上通过重定向保持会话

    Sinatra 不会通过 Chrome 上的重定向来保留我的会话 它正在创建一个全新的会话 而我正在丢失以前的所有会话数据 举个例子 类似于西纳特拉文档 http www sinatrarb com intro Browser 20Redi
  • Javascript - 需要在 setInterval 函数之外使用clearInterval

    基本上 我拥有的是函数内的 setInterval 我想做的是 从外部控制它的行为 这就是我所拥有的 function wheee var i 1 slideee setInterval function sliderContent sty
  • 如何将字节数组转换为 NSString

    我正在从 TCP IP 流读取数据 并成功从预先存在的服务器接收字节数组 我现在正在尝试找到一种方法将该数组转换为NSString 我找到了几个例子 但很难得到我想要的结果 NSData data NSMutableData alloc i
  • npm本地安装

    过去 当我使用 npm gt 1 0 安装软件包时 它们会在本地安装 但现在不再了 我的设置 首先我使用nvm https github com creationix nvm安装node js 我的操作系统 alfred alfred la
  • 检测存在哪些 Unicode 字形?

    JavaScript CSS web 中有没有办法检测系统是否具有某个 Unicode 字符的有效字形 例如 我想检测某种语言中的某个字符是否显示为方框 因为用户没有显示这些 Unicode 点的字体 或者他们是否确实会看到这些字符 这里描
  • 属性与实例变量[重复]

    这个问题在这里已经有答案了 可能的重复 Objective c cocoa cocoa touch 中的 实例变量 和 属性 之间有区别吗 https stackoverflow com questions 843632 is there
  • 如何为 asp.net 身份创建安全标记值 (IUserSecurityStampStore)

    在我的 MVC 5 应用程序中 我必须手动创建安全标记值 身份团队当前的实现似乎使用了指南 Guid NewGuid ToString D 我自己创建一个新的 Guid 来用作新的安全标记值是否安全 或者这是否会在将来的 ASP NET 身
  • Mongo PHP 驱动程序 1.2.10 与 MAMP

    我正在尝试让最新的 Mongo 驱动程序与 OS X 10 5 8 上的 MAMP 1 9 6 一起使用 我从源代码成功构建了它 因为似乎没有预编译版本 将其包含到正确的目录中并重新启动了 apache 但 PHP 无法识别该扩展名 我之前
  • CSS:发光文本,发光非常宽和高

    几天以来我一直在研究 box shadow 和 text shadow 我正在努力获得以下效果 我想要从文字中散发出光芒 a 一度盘旋 很简单 这应该很容易 因为我探索了使用文本阴影 好的 但它适用于小发光 我的意思是 一旦发光较大 由于其
  • Eclipse 在接口方法签名中生成无用的“公共抽象”修饰符

    在使用 Eclipse 重构工具提取方法时 有没有办法阻止生成无用的内容public abstract接口方法签名中的修饰符 谢谢阿列克谢 这听起来像是一个 Eclipse 错误 但它有一个解决方法 该错误自 2004 年 8 月 9 日起
  • CFHTTPMessageAddAuthentication 无法向请求添加身份验证数据

    我正在尝试扩展功能SocketRocket https github com square SocketRocket图书馆 我想添加身份验证功能 由于该库正在使用CFNetwork CFHTTPMessage API https devel
  • 如何在离线服务器上安装 npm -g

    我需要在离线服务器上安装 全局 npm 应用程序 安装普通应用程序很容易 npm install 然后打包生成的文件 手动或使用npm pack 但是 如何安装全局应用程序 具有某种安装脚本 例如forever没有互联网 npm insta
  • 在同一个 R markdown 页面中应用多列划分

    我想如图所示分割我的 Rmarkdown 文档 第一部分为一列 其他部分为两列 used onecolumn and twocolumn但每个部分都是在单个页面中创建的 有解决办法吗 This article https journals
  • 如何在jquery中获取tinymce内容?

    我正在尝试获取tinymce数据 但收到tinyMCE未定义错误 这是我的代码 function savePost console log jQuery wp tinymce editor tinyMCE getContent 请检查 Ti
  • 使用 knockout js 和 jquery ui 滑块

    我试图弄清楚knockout js是否可以很好地解决以下问题 我有多个滑块想要链接到文本框 当文本框更改时 相应的滑块必须更新为新值 反之亦然 更改滑块值或文本框时 需要调用一个函数 该函数使用所有文本框的输入来计算结果 我有我的快速但肮脏
  • 从 Google App Engine (Java) 将文件上传到 Google 云存储

    如何将文件从谷歌应用程序引擎中的servlet上传到谷歌云存储 当我这样做时 Google 云存储不知道文件的类型 即我从 HTML 表单发送的文件 编写 HTML JavaScript 和 servlet 将文件上传到云存储的正确方法是什