Welcome to the new Box Support website. Check out all the details here on what’s changed.

Upload a File - Rest API - C#

Answered
New post

Comments

1 comment

  • Box Product Support

    There were a few details missing, the code is now working:

     

     

    var token = await GetToken();
    
    if (string.IsNullOrWhiteSpace(token)) throw new Exception("Could not obtain Token");
    
    var client = _clientFactory.CreateClient("box-upload");
    
    using var content = new MultipartFormDataContent();
    var attributes = new UploadFileContentAttributes {
     name = fileDto.file.FileName,
      parent = new UploadFileContentParent {
       id = fileDto.folderId
      }
    };
    
    using var jsonContent =
     new StringContent(JsonConvert.SerializeObject(attributes), Encoding.UTF8, "application/json");
    content.Add(jsonContent, "attributes");
    
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(BearerToken, token);
    
    byte[] data;
    using(var br = new BinaryReader(fileDto.file.OpenReadStream())) {
     data = br.ReadBytes((int) fileDto.file.OpenReadStream().Length);
    }
    
    using var bytes = new ByteArrayContent(data);
    
    content.Add(bytes, "file", fileDto.file.FileName);
    
    var response = await client.PostAsync(url, content);
    
    if (!response.IsSuccessStatusCode) throw new Exception(response.ToString());
    
    var jsonString = await response.Content.ReadAsStringAsync();

     

    0
    Comment actions Permalink

Please sign in to leave a comment.