유니티에서 Amazon S3에 업로드할 때 PostObject를 사용하면 파일 업로드에 실패하는 문제

 

 

AWS에서는 유니티에서 AWS 기능들을 사용할 수 있게 해주는 SDK를 제공한다. (AWS에서 제공되는 유니티용 AWS SDK) 해당 SDK에는 AWS의 기능을 유니티에서 사용하는 방법에 대한 샘플 코드 역시 포함되어 있는데, 그 중에서 Amazon S3의 기능을 알려주는 샘플 코드에 문제가 있다.

 

해당 샘플 코드에서는 S3에 등록된 버킷의 목록을 가져오는 법, 버킷에 업로드된 오브젝트의 목록을 가져오는 법, 버킷에 있는 오브젝트를 내려받는 법, 버킷에 새로운 오브젝트를 업로드하는 법, 버킷에 있는 오브젝트를 삭제하는 법에 대한 코드들이 포함되어 있다. 예제를 실행시켜보면 대부분 잘 작동하지만, 버킷에 새로운 오브젝트를 업로드하는 코드만 유독 정상적으로 작동하지 않는다.

 

다음은 문제의 작동하지 않는 코드이다.

 

/// <summary>
/// Post Object to S3 Bucket.
/// </summary>
public void PostObject()
{
    ResultText.text = "Retrieving the file";

    string fileName = SampleFileName;
            
    var stream = new FileStream(Application.dataPath + "/" + fileName, FileMode.Open, FileAccess.Read, FileShare.Read);

    ResultText.text += "\nCreating request object";
    var request = new PostObjectRequest()
    {
        Bucket = S3BucketName,
        Key = fileName,
        InputStream = stream,
        CannedACL = S3CannedACL.Private
    };

    ResultText.text += "\nMaking HTTP post call";

    Client.PostObjectAsync(request, (responseObj) =>
    {
        if (responseObj.Exception == null)
        {
            ResultText.text += string.Format("\nobject {0} posted to bucket {1}", responseObj.Request.Key, responseObj.Request.Bucket);
        }
        else
        {
            ResultText.text += "\nException while posting the result object";
            ResultText.text += string.Format("\n receieved error {0}", responseObj.Response.HttpStatusCode.ToString());
        }
    });
}

 

해당 코드를 실행하면 파일이 Amazon S3에 업로드되어야 하지만 정확한 실패 원인이 나오지 않고 업로드에 실패한다. 아마존 측에서 제공한 API에 문제가 있을 것으로 추정된다. 유니티에서 Amazon S3에 파일을 업로드하기 위해서는 코드를 다음과 같이 변경하여야 한다.

 

 

/// <summary>
/// Put Object to S3 Bucket.
/// </summary>
public void PutObject()
{
    AWSConfigs.HttpClient = AWSConfigs.HttpClientOption.UnityWebRequest;

    ResultText.text = "Retrieving the file";

    string fileName = GetFileHelper();

    var stream = new FileStream(Application.persistentDataPath + Path.DirectorySeparatorChar + fileName, FileMode.Open, FileAccess.Read, FileShare.Read);

    ResultText.text += "\nCreating request object";
    var request = new PutObjectRequest()
    {
        BucketName = S3BucketName,
        Key = fileName,
        InputStream = stream,
        CannedACL = S3CannedACL.Private
    };

    ResultText.text += "\nMaking HTTP post call";
    Client.PutObjectAsync(request, (responseObj) =>
    {
        if (responseObj.Exception == null)
        {
            ResultText.text += string.Format("\nobject {0} puted to bucket {1}", responseObj.Request.Key, responseObj.Request.BucketName);
        }
        else
        {
            ResultText.text += "\nException while puting the result object";
            ResultText.text += string.Format("\n receieved error {0}", responseObj.Response.HttpStatusCode.ToString());
        }
    });
}

 

위의 코드와 같이 PostObject 대신에 PutObject를 사용해야 Amazon S3에 파일 업로드가 정상적으로 되는 것을 확인할 수 있다.

 


 

참고

 

(AWS) 유니티에서 S3에 업로드하기

사흘 간 헤매던 원인을 해결해서 매우 기분이 좋다. 결론적으로 말하면 AWS에서 제공하는 Unity SDK...

blog.naver.com

 

 

[유니티 어필리에이트 프로그램]

아래의 링크를 통해 에셋을 구매하시거나 유니티를 구독하시면 수익의 일부가 베르에게 수수료로 지급되어 채널의 운영에 도움이 됩니다.

 

에셋스토어

여러분의 작업에 필요한 베스트 에셋을 찾아보세요. 유니티 에셋스토어가 2D, 3D 모델, SDK, 템플릿, 툴 등 여러분의 콘텐츠 제작에 날개를 달아줄 다양한 에셋을 제공합니다.

assetstore.unity.com

 

Easy 2D, 3D, VR, & AR software for cross-platform development of games and mobile apps. - Unity Store

Have a 2D, 3D, VR, or AR project that needs cross-platform functionality? We can help. Take a look at the easy-to-use Unity Plus real-time dev platform!

store.unity.com

 

Create 2D & 3D Experiences With Unity's Game Engine | Unity Pro - Unity Store

Unity Pro software is a real-time 3D platform for teams who want to design cross-platform, 2D, 3D, VR, AR & mobile experiences with a full suite of advanced tools.

store.unity.com

[투네이션]

 

-

 

toon.at

[Patreon]

 

WER's GAME DEVELOP CHANNEL님이 Game making class videos 창작 중 | Patreon

WER's GAME DEVELOP CHANNEL의 후원자가 되어보세요. 아티스트와 크리에이터를 위한 세계 최대의 멤버십 플랫폼에서 멤버십 전용 콘텐츠와 체험을 즐길 수 있습니다.

www.patreon.com

[디스코드 채널]

 

Join the 베르의 게임 개발 채널 Discord Server!

Check out the 베르의 게임 개발 채널 community on Discord - hang out with 399 other members and enjoy free voice and text chat.

discord.com

 

반응형

안드로이드 버전의 빌드에서 디바이스의 로컬 저장소에 파일을 저장하는 법

 

유니티에서 게임을 만들 때, 네트워크로 받아온 파일을 로컬에 저장해야 하는 일이 많다. 특히 게임의 패치 시스템(Patch System)을 만들어야 하는 경우라면 100% 필요한 일이다. 윈도우 버전의 빌드에서는 적당히 원하는 경로에 파일을 저장할 수 있지만, 안드로이드 버전의 빌드에서는 경로마다 읽기/쓰기의 권한이 다르고 제한이 있다.

 

안드로이드의 데이터 경로와 읽기/쓰기 권한은 다음과 같다.

 

[안드로이드 External]
Application.persistentDataPath : /mnt/sdcard/Android/data/com.YourProductName.YourCompanyName/files [파일 읽기/쓰기 가능]
Application.dataPath : /data/app/번들이름-번호.apk
Application.streamingAssetsPath : jar:file:///data/app/번들이름.apk!/assets [파일이 아닌 WWW로 읽기 가능]

[안드로이드 Internal]
Application.persistentDataPath : /Android/data/com.YourProductName.YourCompanyName/files [파일 읽기/ 쓰기 가능]
Application.dataPath : /data/app/번들이름-번호.apk
Application.streamingAssetsPath : jar:file:///data/app/번들이름.apk!/assets [파일이 아닌 WWW로 읽기 가능]

 

위에 적힌 것처럼 네트워크에서 받아온 파일을 로컬에 저장하기 위해서는 읽기/쓰기가 모두 가능한 Application.persistentDataPath의 경로를 사용해야 한다.

 

위의 경로에 원하는 폴더를 만들고자 할 때는 다음의 코드를 참조하면 된다.

 

if (!Directory.Exists(Application.persistentDataPath + "/생성할 폴더 이름"))
{
    Directory.CreateDirectory(Application.persistentDataPath + "/생성할 폴더 이름");
}

 

위의 경로에 원하는 파일을 쓰고자 할 때는 다음의 코드를 참조하면 된다.

 

FileStream fs = new FileStream(Application.persistentDataPath + "/" + "TestFileName.txt", FileMode.Create, FileAccess.Write);
byte[] data = new byte[writeDataSize];
fs.Write(data, 0, (int)writeDataSize);
fs.Close();

 

이 섹션에서 소개한 내용은 제일 처음에 설명했듯이 주로 게임 패치 시스템에 많이 사용되는데, 유니티에서는 게임 패치에 에셋 번들을 많이 사용하는 편이다. 빌드된 에셋 번들은 manifest 파일을 제외하면 공통적으로 나오는 AssetBundles 파일을 비롯해서 주로 확장자 없이 지정한 번들 이름만 적힌 파일이 나오는데, 이렇게 확장자가 없는 에셋 번들 파일을 그대로 사용할 때는, 각 에셋 번들의 이름과 같은 폴더를 생성하려고 하면 폴더 생성에 실패하게 된다. 그렇기 때문에, 에셋 번들의 이름과 같은 이름의 폴더의 생성은 피하거나 에셋 번들 파일의 끝에 ".unity3d"같은 확장자를 붙여주는 것이 좋다.

 


참고 사이트

 

# Uniyt3D 게임엔진 예약된 폴더이름 및 데이터 경로 정리.

[윈도우 에디터]Application.persistentDataPath : 사용자디렉토리/AppData/LocalLow/회사이름/프로덕트이름 파일 읽기 쓰기 가능Application.dataPath : 프로젝트디렉토리/AssetsApplication.streamingAssetsPath : 프로젝트디

egloos.zum.com

 

 

[유니티 어필리에이트 프로그램]

아래의 링크를 통해 에셋을 구매하시거나 유니티를 구독하시면 수익의 일부가 베르에게 수수료로 지급되어 채널의 운영에 도움이 됩니다.

 

에셋스토어

여러분의 작업에 필요한 베스트 에셋을 찾아보세요. 유니티 에셋스토어가 2D, 3D 모델, SDK, 템플릿, 툴 등 여러분의 콘텐츠 제작에 날개를 달아줄 다양한 에셋을 제공합니다.

assetstore.unity.com

 

Easy 2D, 3D, VR, & AR software for cross-platform development of games and mobile apps. - Unity Store

Have a 2D, 3D, VR, or AR project that needs cross-platform functionality? We can help. Take a look at the easy-to-use Unity Plus real-time dev platform!

store.unity.com

 

Create 2D & 3D Experiences With Unity's Game Engine | Unity Pro - Unity Store

Unity Pro software is a real-time 3D platform for teams who want to design cross-platform, 2D, 3D, VR, AR & mobile experiences with a full suite of advanced tools.

store.unity.com

[투네이션]

 

-

 

toon.at

[Patreon]

 

WER's GAME DEVELOP CHANNEL님이 Game making class videos 창작 중 | Patreon

WER's GAME DEVELOP CHANNEL의 후원자가 되어보세요. 아티스트와 크리에이터를 위한 세계 최대의 멤버십 플랫폼에서 멤버십 전용 콘텐츠와 체험을 즐길 수 있습니다.

www.patreon.com

[디스코드 채널]

 

Join the 베르의 게임 개발 채널 Discord Server!

Check out the 베르의 게임 개발 채널 community on Discord - hang out with 399 other members and enjoy free voice and text chat.

discord.com

 

반응형

+ Recent posts