File Upload

Pre-requisites

  • All authorized users can use this endpoint.

URI

To use this endpoint you send a POST request to:

  • /api/file/file-upload

Request Headers

The following request headers must be included in your request:

Field Description
Authorization Please see the Authorization guide for more information on building the Authorization header.
x-mc-req-id

A randomly generated GUID, for example,

8578FCFC-A305-4D9A-99CB-F4D5ECEFE297
x-mc-app-id The Application ID provided with your Registered API Application.
x-mc-date The current date and time in the following format, for example,
Tue, 24 Nov 2015 12:50:11 UTC
x-mc-arg The sha256 and file size of the file to upload included in the following construct: {'data': [{'sha256': '" + the sha256 hash + "', 'fileSize': " + the file size + "}]}"

Request Body

The file to upload.

Response

{
  "meta" : {
    "status" : Number
  },
  "data" : [ {
    "id" : "String"
  } ],
  "fail" : [ ]
}
meta object
Field Type Description
status Number The function level status of the request.
data array
Field Type Description
id String The Mimecast ID of the file.
fail array

When a request is successful the fail array will be empty.

Field Type Description
errors Array of error objects An array of error objects describing the error returned from the API.

errors object

Field Type Description
message String The error message.
code String The Mimecast code associated with the error.
retryable Boolean If the error is retryable

Sample Code

Sample code is provided to demonstrate how to use the API and is not representative of a production application. To use the sample code; complete the required variables as described, populate the desired values in the request body, and execute in your favorite IDE.  Please see the Global Base URL's page to find the correct base URL to use for your account.

POST {base_url}/api/file/file-upload
Authorization: MC {accesskKey}:{Base64 encoded signed Data To Sign}
x-mc-date: {dateTime}
x-mc-req-id: {unique id}
x-mc-app-id: {applicationId}
Content-Type: application/json
Accept: application/json

FILE TO UPLOAD
import base64
import hashlib
import hmac
import uuid
import datetime
import requests

# Setup required variables
base_url = "https://xx-api.mimecast.com"
uri = "/api/file/file-upload"
url = base_url + uri
access_key = "YOUR ACCESS KEY"
secret_key = "YOUR SECRET KEY"
app_id = "YOUR APPLICATION ID"
app_key = "YOUR APPLICATION KEY"
file_name = 'PATH TO FILE'

# Generate request header values
request_id = str(uuid.uuid4())
hdr_date = datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S") + " UTC"

# DataToSign is used in hmac_sha1
dataToSign = ':'.join([hdr_date, request_id, uri, app_key])

# Create the HMAC SHA1 of the Base64 decoded secret key for the Authorization header
hmac_sha1 = hmac.new(base64.b64decode(secret_key), dataToSign.encode(), digestmod=hashlib.sha1).digest()

# Use the HMAC SHA1 value to sign the hdrDate + ":" requestId + ":" + URI + ":" + appkey
sig = base64.b64encode(hmac_sha1).rstrip()

# Generate the sha256 of the file to include in the request headers
sha256 = hashlib.sha256()
with open(file_name, 'rb') as f:
    for block in iter(lambda: f.read(65536), b''):
        sha256.update(block)

# Create request headers
headers = {
    'Authorization': 'MC ' + access_key + ':' + sig.decode(),
    'x-mc-app-id': app_id,
    'x-mc-date': hdr_date,
    'x-mc-req-id': request_id,
    'Content-Type': 'application/octet-stream',
    'x-mc-arg': '{\'data\': [{\'sha256\': \'' + sha256.hexdigest() + '\', \'fileSize\': '
                + str(os.path.getsize(file_name)) + '}]}'
}

# Read the file to set in the request payload
payload = open(file_name, 'rb').read()

r = requests.post(url=url, headers=headers, data=payload)

print(r.text)
static void Main(string[] args)
        {
            //Setup required variables
            string baseUrl = "https://xx-api.mimecast.com";
            string uri = "/api/file/file-upload";
            string accessKey = "YOUR ACCESS KEY";
            string secretKey = "YOUR SECRET KEY";
            string appId = "YOUR APPLICATION ID";
            string appKey = "YOUR APPLICATION KEY";
            string fileName = "PATH TO FILE";

            //Generate request header values
            string hdrDate = System.DateTime.Now.ToUniversalTime().ToString("R");
            string requestId = System.Guid.NewGuid().ToString();

            //Generate sha256 of the file to upload
            string sha256 = generateSha256(fileName);

            //Get the file size of the file to upload
            long fileSize = new System.IO.FileInfo(fileName).Length;

            //Create the HMAC SHA1 of the Base64 decoded secret key for the Authorization header
            System.Security.Cryptography.HMAC h = new System.Security.Cryptography.HMACSHA1(System.Convert.FromBase64String(secretKey));

            //Use the HMAC SHA1 value to sign the hdrDate + ":" requestId + ":" + URI + ":" + appkey
            byte[] hash = h.ComputeHash(System.Text.Encoding.Default.GetBytes(hdrDate + ":" + requestId + ":" + uri + ":" + appKey));

            //Build the signature to be included in the Authorization header in your request
            string signature = "MC " + accessKey + ":" + System.Convert.ToBase64String(hash);

            //Build Request
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(baseUrl + uri);
            request.Method = "POST";
            request.ContentType = "application/octet-stream";

            //Add Headers
            request.Headers[System.Net.HttpRequestHeader.Authorization] = signature;
            request.Headers.Add("x-mc-date", hdrDate);
            request.Headers.Add("x-mc-req-id", requestId);
            request.Headers.Add("x-mc-app-id", appId);
            request.Headers.Add("x-mc-arg", "{'data': [{'sha256': '" + sha256 + "', 'fileSize': " + fileSize.ToString() + "}]}");

            //Add request body
            //Create and write data to stream
            var payload = System.IO.File.ReadAllBytes(fileName);

            System.IO.Stream stream = request.GetRequestStream();
            stream.Write(payload, 0, payload.Length);
            stream.Close();

            //Send Request
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

            //Output response to console
            System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
            string responseBody = "";
            string temp = null;
            while ((temp = reader.ReadLine()) != null)
            {
                responseBody += temp;
            };
            System.Console.WriteLine(responseBody);
            System.Console.ReadLine();
        }

        public static string generateSha256(string fileName) {
            using (System.IO.FileStream post_stream = System.IO.File.OpenRead(fileName))
            {
                System.Security.Cryptography.SHA256Managed sha = new System.Security.Cryptography.SHA256Managed();
                byte[] file_hash = sha.ComputeHash(post_stream);
                return System.BitConverter.ToString(file_hash).Replace("-", System.String.Empty);
            }
        }
#Setup required variables
$baseUrl = "https://xx-api.mimecast.com"
$uri = "/api/file/file-upload"
$url = $baseUrl + $uri
$accessKey = "YOUR ACCESS KEY"
$secretKey = "YOUR SECRET KEY"
$appId = "YOUR APPLICATION ID"
$appKey = "YOUR APPLICATION KEY"
$filename = "PATH TO FILE"

#Generate request header values
$hdrDate = (Get-Date).ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss UTC")
$requestId = [guid]::NewGuid().guid

#Create the HMAC SHA1 of the Base64 decoded secret key for the Authorization header
$sha = New-Object System.Security.Cryptography.HMACSHA1
$sha.key = [Convert]::FromBase64String($secretKey)
$sig = $sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($hdrDate + ":" + $requestId + ":" + $uri + ":" + $appKey))
$sig = [Convert]::ToBase64String($sig)

#Generate sha256 of file to upload
$sha256 = Get-FileHash $filename
$fileSize = Get-Item $filename
$fileSize = $fileSize.length

#Create Headers
$headers = @{"Authorization" = "MC " + $accessKey + ":" + $sig;
                "x-mc-date" = $hdrDate;
                "x-mc-app-id" = $appId;
                "x-mc-req-id" = $requestId;
                "Content-Type" = "application/octet-stream";
                "x-mc-arg" = "{'data': [{'sha256': '" + $sha256.Hash + "', 'fileSize': " + $fileSize + "}]}";
                }

#Create post body
$fileParams = @{
    Path = $filename
    Raw = $true
}
if ($PSVersionTable.PSVersion.Major -ge 6) {
    $fileParams.AsByteStream = $true
}
else {
    $fileParams.Encoding = "Byte"
}
$postBody = Get-Content @fileParams

#Send Request
$response = Invoke-RestMethod -Method Post -Headers $headers -Body $postBody -Uri $url

#Print the response
$response
public static void main(String[] args) throws java.io.IOException, java.security.NoSuchAlgorithmException, java.security.InvalidKeyException {

        //set up variables for request
        String baseUrl = "https://xx-api.mimecast.com";
        String uri = "/api/file/file-upload";
        String url = "https://" + baseUrl + uri;
        String accessKey = "YOUR ACCESS KEY";
        String secretKey = "YOUR SECRET KEY";
        String appId = "YOUR APPLICATION ID";
        String appKey = "YOUR APPLICATION KEY";
        String filePath = "PATH TO FILE";

        // generate sha256 of file to upload
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-256");
        java.io.FileInputStream fis = new java.io.FileInputStream(filePath);

        byte[] dataBytes = new byte[1024];

        int nread = 0;
        while ((nread = fis.read(dataBytes)) != -1) {
            md.update(dataBytes, 0, nread);
        };
        byte[] mdbytes = md.digest();

        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mdbytes.length; i++) {
            sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
        }

        String sha256 = sb.toString();

        // get file size of file to upload
        java.io.File fileToUpload = new java.io.File(filePath);
        double fileSize = fileToUpload.length();

        //create URL object
        java.net.URL obj = new java.net.URL(url);

        // set guid for x-mc-req-id header
        String guid = java.util.UUID.randomUUID().toString();

        // set date for x-mc-date header
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
        sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
        String date = sdf.format(new java.util.Date());

        //create signature for the Authorization header
        String dataToSign = date + ":" + guid + ":" + uri + ":" + appKey;
        String hmacSHA1 = "HmacSHA1";
        javax.crypto.spec.SecretKeySpec signingKey = new javax.crypto.spec.SecretKeySpec(org.apache.commons.codec.binary.Base64.decodeBase64(secretKey.getBytes()), hmacSHA1);
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance(hmacSHA1);
        mac.init(signingKey);
        String sig = new String(org.apache.commons.codec.binary.Base64.encodeBase64(mac.doFinal(dataToSign.getBytes())));

        // create request object
        javax.net.ssl.HttpsURLConnection con = (javax.net.ssl.HttpsURLConnection) obj.openConnection();

        //set request type to POST
        con.setRequestMethod("POST");
        con.setDoOutput(true);

        //add reuqest headers
        con.setRequestProperty("Authorization", "MC " + accessKey + ":" + sig);
        con.setRequestProperty("x-mc-req-id", guid);
        con.setRequestProperty("x-mc-app-id", appId);
        con.setRequestProperty("x-mc-date", date);
        con.setRequestProperty("Content-Type", "application/octet-stream");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestProperty("x-mc-arg", "{'data': [{'sha256': '" + sha256 + "', 'fileSize': " + String.valueOf(fileSize) + "}]}");

        //Add post body to the request
        java.io.OutputStream outstream = con.getOutputStream();
        java.io.InputStream istream = new java.io.FileInputStream(fileToUpload);
        int c;
        final int EOF = -1;
        while ((c = istream.read()) != EOF)
            outstream.write(c);
        istream.close();
        outstream.close();

        //process response
        java.io.BufferedReader in = new java.io.BufferedReader(
                new java.io.InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //return result
        java.lang.System.out.println(response.toString());
    }
Back to Top