cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
cpoole2256
Community Participant

Create Text File Directly Into Folder System

Hello Canvas Developers,

I know its possible to upload a file to Canvas using the API, but is there an API call to create a simple text file directly in the Canvas folder system without having to go through the process of creating it on my end? 

Thanks for the help,

-Christopher Poole

Labels (2)
Tags (2)
0 Kudos
3 Replies
ColinMurtaugh
Community Champion

Hi Christopher --

The short answer is yes, you can programmatically create files in Canvas user or course file structure -- there's some documentation on the process here: Uploading Files - Canvas LMS REST API Documentation 

In the second step of that process, you POST the file data to the URL that's provided by Canvas.  When you make that POST request, you could dynamically create the contents of the file and include it in the request body.  We do something like this to upload our user profile photos, which are stored in a database locally. We essentially read the image data from the database and POST it as the contents of a JPG file that we place in each user's file folder.  This way we skip the step of actually creating a JPG file on disk locally.

I hope this helps -- let me know if you'd like any more detail!

--Colin

What specific argument do I need to set to give it my file's text? I've supplied all the other arguments (including the copy of upload_params). I tried using "file" like it says to do for a file upload from within the same folder (the documentation's example is "file=@myfile.jpg"), but this gives me a 500 Internal Server Error (I replaced "@myfile" with the text of my file").

Also, in regards to the 3rd step, it talks about getting either a 3XX response code or a 201, but how would I test my code for both? The instance I've set up is from bitnami and doesn't use anything fancy like Amazon S3 bucket. I'll probably post this as a separate question, but if you've got an answer right away I'd appreciate it!

cpoole2256
Community Participant

Never mind I fixed it. I was using UnityWebRequest and WWWForms. I was using .AddField() for WWWForms which takes a string parameter for the data. I learned just now that there is a different .AddBytes() function that I should have been using for this file data! So basically I was trying to send my data as text instead of bytes. Easy fix!

After I got that done I ran into this problem: https://community.canvaslms.com/thread/10843 of getting "200" back as my response. This is because it tries to redirect for you when you get 300 errors. To fix this in Unity, just add .redirectLimit = 0 to your UnityWebRequest. This will give you the correct 30X error and then you can use .GetResponseHeader("Location") to get the url where you have to send that one final POST to. 

That was very Unity specific, but hope I could help anyone whose randomly having the same problems I was!

-Chris