Cloudupload
Cloudupload
' This example uses a previously obtained access token having permission for the
' scope "https://www.googleapis.com/auth/cloud-platform"
' In this example, Get Google Cloud Storage OAuth2 Access Token,
' the service account access token was saved to a text file. This example fetches the acc
Dim sbToken As New Chilkat.StringBuilder
sbToken.LoadFile("qa_data/tokens/googleCloudStorageAccessToken.txt","utf-8")
Exit Sub
End If
o?uploadType=media&name=[OBJECT_NAME]"
me=object_name")
POST is sent.
",443,True,req)
n/o/penguins.jpg",
ilkat-ocean/o/penguins.jpg?generation=1502643657837855&alt=media",
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<form id="Form1" method="post" enctype="multipart/form-data" runat="server">
<input type=file id=File1 name=File1 runat="server" />
//Disclaimer -- I should have used the Html helper for this but i was being lazy. /Ajax/AddAttachment is the Controlle
Copy Code
[HttpPost]
public ActionResult AddAttachment(string IssueID, IEnumerable<HttpPostedFileBase> files)
{
using (UnitOfWork uow = new UnitOfWork())
{
if (files != null)
{
foreach (var file in files)
{
if (file != null)
{
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath("~/Content/attachments"), fileName);
file.SaveAs(path);
if (System.IO.File.Exists(path))
{
string filename = string.Format(@"{0}{1}", Guid.NewGuid().ToString(), Path
System.IO.File.Move(path, Path.Combine(Server.MapPath("~/Content/attachmen
path = Path.Combine(Server.MapPath("~/Content/attachments"), filename);
}
}
}
}
}
return RedirectToAction("View", "Controller", new { @id = IssueID });
}
}
Submit1"/>
="/Ajax/AddAttachment">
D" value="@Model.IndexID" />
se> files)
ttachments"), fileName);
wGuid().ToString(), Path.GetExtension(fileName));
ath("~/Content/attachments"), filename));
chments"), filename);
DROPBOX
ONEDRIVE
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Drive.v3
Imports Google.Apis.Drive.v3.Data
Imports Google.Apis.Services
Imports Google.Apis.Util.Store
Imports System.IO
Imports System.Threading
Module Module1
Dim Scopes() As String = {DriveService.Scope.Drive}
Dim ApplicationName As String = "Your-Application-Name"
Private Service As DriveService = New DriveService
End Using
'Create Drive API service.
Dim Service = New DriveService(New BaseClientService.Initializer() With
{
.HttpClientInitializer = creds,
.ApplicationName = ApplicationName
})
'Define parameters of request here, depending on whether you need to use
'the get or export methods
Dim fileId As String = "your-file-id"
Post Views: 7,927
Hello Friends, It’s being very long time and I haven’t shared anything. But today I am going to share how
Step 1: Create Bucket
Step 2: Make Bucket Public
Step 3: Create Service Account & Download Key
Step 4: Install Composer & Download Google Cloud Storage Library
Step 5: Make Code Ready
Step 6: Upload File
Step 1: Create Bucket
First of all we have to create a bucket in which we will upload/store our files. Buckets are the basic conta
Step 2: Make Bucket Public
After creating bucket our next step is to making it public so that we can access it’s object/files at third pa
requests.php
1 <?php
2 include_once 'config.php';
3
4 $action = filter_var(trim($_REQUEST['action']), FILTER_SANITIZE_STRING);
5 if ($action == 'upload') {
6 $response['code'] = "200";
7 if ($_FILES['file']['error'] != 4) {
8 //set which bucket to work in
9 $bucketName = "cloud-test-bucket-1";
10 // get local file for upload testing
11 $fileContent = file_get_contents($_FILES["file"]["tmp_name"]);
12 // NOTE: if 'folder' or 'tree' is not exist then it will be automatically created !
13 $cloudPath = 'uploads/' . $_FILES["file"]["name"];
14
15 $isSucceed = uploadFile($bucketName, $fileContent, $cloudPath);
16
17 if ($isSucceed == true) {
18 $response['msg'] = 'SUCCESS: to upload ' . $cloudPath . PHP_EOL;
19 // TEST: get object detail (filesize, contentType, updated [date], etc.)
20 $response['data'] = getFileInfo($bucketName, $cloudPath);
21 } else {
22 $response['code'] = "201";
23 $response['msg'] = 'FAILED: to upload ' . $cloudPath . PHP_EOL;
24 }
25 }
26 header("Content-Type:application/json");
27 echo json_encode($response);
28 exit();
29 }
index.php
1 <html>
2 <head>
3 <meta charset="UTF-8">
4 <title>GCP Storage File Upload using PHP</title>
5 </head>
6 <body>
7 <form id="fileUploadForm" method="post" enctype="multipart/form-data">
8 <input type="file" name="file"/>
9 <input type="submit" name="upload" value="Upload"/>
10 <span id="uploadingmsg"></span>
11 <hr/>
12 <strong>Response (JSON)</strong>
13 <pre id="json">json response will be shown here</pre>
14
15 <hr/>
16 <strong>Public Link</strong> <span>(https://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME])</span><br/>
17 <b>Note:</b> we can use this link only if object or the whole bucket has made public, which in our case has already made buck
18 <div id="output"></div>
19 </form>
20 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZ
21 <script>
22 $("#fileUploadForm").submit(function (e) {
23 e.preventDefault();
24 var action = "requests.php?action=upload";
25 $("#uploadingmsg").html("Uploading...");
26 var data = new FormData(e.target);
27 $.ajax({
28 type: 'POST',
29 url: action,
30 data: data,
31 /*THIS MUST BE DONE FOR FILE UPLOADING*/
32 contentType: false,
33 processData: false,
34 }).done(function (response) {
35 $("#uploadingmsg").html("");
36 $("#json").html(JSON.stringify(response, null, 4));
37 //https://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME]
38 $("#output").html('<a href="https://storage.googleapis.com/' + response.data.bucket + '/' + response.data.name + '"><i>https:
39 if(response.data.contentType === 'image/jpeg' || response.data.contentType === 'image/jpg' || response.data.contentType ===
40 $("#output").append('<br/><img src="https://storage.googleapis.com/' + response.data.bucket +
41 }
42 }).fail(function (data) {
43 //any message
44 });
45 });
46 </script>
47 </body>
48 </html>
Step 6: Upload File
Step 1
Step 2
Step 3
Note: –
Normally we can upload and download any type of file on Google Cloud Storage but if we want to load file using javascript
1. Check current configuration using below command
1[
2 {
3 "origin": ["https://zatackcoder.com", "https://zatackcoder.com"],
4 "responseHeader": ["Content-Type"],
5 "method": ["GET"],
6 "maxAgeSeconds": 3600
7 }
8]
3. Change current configuration using below command
1 (await fetch('https://storage.googleapis.com/cloud-test-bucket-1/uploads/gull.jpg'))
Before CORS Configuration
References:-
https://cloud.google.com/storage/
https://cloud.google.com/storage/docs/key-terms#buckets
https://cloud.google.com/storage/docs/creating-buckets
https://cloud.google.com/cloud-console/
https://cloud.google.com/shell/
https://cloud.google.com/storage/docs/access-control/making-data-public
https://cloud.google.com/iam/docs/service-accounts
https://cloud.google.com/iam/docs/creating-managing-service-account-keys
https://getcomposer.org/
https://googleapis.github.io/google-cloud-php/
https://cloud.google.com/iam/docs/creating-managing-service-accounts
https://cloud.google.com/iam/docs/granting-roles-to-service-accounts
https://cloud.google.com/iam/docs/creating-managing-service-account-keys#iam-service-account-keys-create-gcloud
Post navigation
Previous article
Adding Animations to Controls or Layouts in Android
ext article
ations Built using Java
Comments
Disqus Comments
Facebook Comments
Comments
Powered by
Translate
ADVERTISEMENT
RECENT POSTS
TOP DOWNLOADS
Calculator in JavaFX
DOWNLOAD
110370 downloads184.55 KB
Browser
DOWNLOAD
96543 downloads201.60 KB
Image Gallery App Android Studio Project
DOWNLOAD
90126 downloads18.50 MB
kets are the basic containers that hold your data. Everything that you store in Cloud Storage must be contained in a
object/files at third party hosting or at localhost using uri like “https://storage.googleapis.com/[BUCKET_NAM
can use that private key to connect to Google Cloud Storage. Below screenshot or command will help us to create
r download Google Cloud Storage Library which we are going to use in our code and to download it, we’ll use Terminal (Command Lin
code small as possible so that we can easily upload our code on third party hosting if needed. Composer will download latest stable ve
ests.php, index.php and will upload file through ajax. Here config.php will contain private key and necessary func
ERVICE-ACCOUNT-EMAIL]"
ECT_NAME])</span><br/>
our case has already made bucket public<br/>
tegrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
must be contained in a bucket. To know more about bucket click buckets link in this paragraph. Below screenshot w
om/[BUCKET_NAME]/[OBJECT_NAME]”. Here also below screenshot will help us to make bucket public or
download latest stable version of Google Cloud Storage library after executing above command. After download finishes will have a fo
key and necessary functions, requests.php will use to handle ajax request to upload file and index.php for sending a
read file due to CORS policy, so to solve this problem we need create a configuration file to allow one or more domain to access files u
p, xampp, etc) to Google Cloud Storage. To upload files on Google Cloud Storage we are going to follow below ste
ph. Below screenshot will help us to create bucket from GCP Console or we can execute “gsutil mb gs://[BUCKE
make bucket public or we can make it public using “gsutil acl ch -u AllUsers:R gs://[BUCKET_NAME]/” comm
ject folder if already created then we’ll run below command.
nload finishes will have a folder called ‘vendor’ containing library files, we don’t need to change anything inside it.