C#和Mapbox Tileset上传API

时间:2019-01-11 03:45:47

标签: c# amazon-web-services upload mapbox

原始问题已解决,因此可以与他人共享:

.NET Core v2.0(旨在作为AWS Lambda运行),但不仅限于此。

在实现上有一定的灵活性; (希望)易于阅读。


我的最终目标是通过Lambda将kml(或其他)文件从云上传到Mapbox。目前正在本地测试我的C#控制台应用程序,仅尝试移动本地文件。

我一直关注API documentation from Mapbox,并且(进行了一些调整)获得了单独的cURL版本,以正常工作。我使用了有效的cURL版本,文档以及与该主题有关的另一个SO用户自己的问题12作为指导。

namespace MapboxTilesetUploader
{
class Function
{
public static string mbxUsername = "{your-mapbox-username}";
public static string mbxAccessToken = "{your-mapbox-secret-token}";
public static string file = "{filepath-to-your-file}";
public static string htmlFile = "{location-of-your-file}";

public static void Main()
{
    Mapbox mapbox = new Mapbox(mbxUsername, mbxAccessToken);

    mapbox.GetS3Credentials();

    // If getting file from a local source
    mapbox.StageFileToS3(file);

    // If getting file from a non-local source
    // Stream stream = Mapbox.GetStreamFromUrl(htmlFile);
    // var responseStageFileToS3 = mapbox.StageFileToS3Async(stream).Result;


    /* forces the response to finish, otherwise no upload to Mapbox will occur */
    var responseString = mapbox.UploadS3FileToMapboxAsync("my-tileset", "file-title").Result;
}
}
class Mapbox
{
private string m_mbxUsername;
private string m_mbxAccessToken;
private string m_mbxApiCredentialsUri;
private string m_mbxApiUploadUri;

private static readonly HttpClient client = new HttpClient();

public Mapbox(string mbxUsername, string mbxAccessToken)
{
    m_mbxUsername = mbxUsername;
    m_mbxAccessToken = mbxAccessToken;
    m_mbxApiCredentialsUri = "https://api.mapbox.com/uploads/v1/" + mbxUsername + "/credentials?access_token=" + mbxAccessToken;
    m_mbxApiUploadUri = "https://api.mapbox.com/uploads/v1/" + mbxUsername + "?access_token=" + mbxAccessToken;
}
public void GetS3Credentials()
{
    /* https: //api.mapbox.com/uploads/v1/{mbxUsername}/credentials?access_token={mbxAccessToken} */
    var request = (System.Net.HttpWebRequest)WebRequest.Create(m_mbxApiCredentialsUri);
    request.AutomaticDecompression = DecompressionMethods.GZip;

    using (var response = (HttpWebResponse)request.GetResponse())
    {
        using (var stream = response.GetResponseStream())
        {
            if (stream != null)
            {
                using (var reader = new StreamReader(stream))
                {
                    var result = reader.ReadToEnd();
                    var mapboxS3Credentials = JObject.Parse(result);

                    MapboxS3Credentials.accessKeyId = (string)mapboxS3Credentials["accessKeyId"];
                    MapboxS3Credentials.bucket = (string)mapboxS3Credentials["bucket"];
                    MapboxS3Credentials.key = (string)mapboxS3Credentials["key"];
                    MapboxS3Credentials.secretAccessKey = (string)mapboxS3Credentials["secretAccessKey"];
                    MapboxS3Credentials.sessionToken = (string)mapboxS3Credentials["sessionToken"];
                    MapboxS3Credentials.url = (string)mapboxS3Credentials["url"];
                }
            }
        }
    }
}
public void StageFileToS3(string filepath)
{
    var s3client = new AmazonS3Client(
        MapboxS3Credentials.accessKeyId,
        MapboxS3Credentials.secretAccessKey,
        MapboxS3Credentials.sessionToken, 
        Amazon.RegionEndpoint.USEast1);

    try
    {
        PutObjectRequest putRequest = new PutObjectRequest
        {
            BucketName = MapboxS3Credentials.bucket,
            Key = MapboxS3Credentials.key,
            FilePath = filepath,
            ContentType = "text/plain"
        };

        PutObjectResponse response = s3client.PutObjectAsync(putRequest).Result;
    }
    catch (AmazonS3Exception amazonS3Exception)
    {
        throw new Exception("Error occurred: " + amazonS3Exception.Message);
    }
}
// If getting file from a stream
public static MemoryStream GetStreamFromUrl(string url)
{
        byte[] streamBytes = null;
        MemoryStream streamData = null;

        try
        {
            using (var webClient = new WebClient())
            {
                streamBytes = webClient.DownloadData(url);
            }
            streamData = new MemoryStream(streamBytes);

        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception getting stream from url: " + ex);
        }
        return streamData;
    }
// If getting file from a stream
public async Task<PutObjectResponse> StageFileToS3Async(Stream stream)
    {
        var s3client = new AmazonS3Client(
            MapboxS3Credentials.accessKeyId,
            MapboxS3Credentials.secretAccessKey,
            MapboxS3Credentials.sessionToken,
            Amazon.RegionEndpoint.USEast1);

        try
        {
            PutObjectRequest putRequest = new PutObjectRequest
            {
                BucketName = MapboxS3Credentials.bucket,
                Key = MapboxS3Credentials.key,
                InputStream = stream,
            };

            PutObjectResponse response = await s3client.PutObjectAsync(putRequest);
            return response;

        }
        catch (AmazonS3Exception amazonS3Exception)
        {
            throw new Exception("Error occurred: " + amazonS3Exception.Message);
        }
    }
public async Task<HttpResponseMessage> UploadS3FileToMapboxAsync(string setTilesetName, string setCustomName = null)
{

    /* 
   "tileset": "username.custom-tileset-name",
   "url": "https://{bucket}.s3.amazonaws.com/{key}",
   "name": "{custom-name}"
    */

Dictionary<string, string> content = new Dictionary<string, string>() {
    { "tileset", m_mbxUsername + "." + setTilesetName },
    { "url", "https://" + MapboxS3Credentials.bucket + ".s3.amazonaws.com/" + MapboxS3Credentials.key },
    { "name", setCustomName } };

    var encodedContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");

    var response = await client.PostAsync(m_mbxApiUploadUri, encodedContent);

    return response;
}
static class MapboxS3Credentials
{
    public static string accessKeyId;
    public static string bucket;
    public static string key;
    public static string secretAccessKey;
    public static string sessionToken;
    public static string url;
}
}

0 个答案:

没有答案