/// <summary> /// Uploads a provided file to the target parent folder /// If the file already exists, an error will be thrown. /// A proper timeout should be provided for large uploads /// </summary> /// <param name="fileRequest"></param> /// <param name="stream"></param> /// <param name="timeout"></param> /// <returns></returns> public async Task <BoxFile> UploadAsync(BoxFileRequest fileRequest, Stream stream, List <string> fields = null, TimeSpan?timeout = null) { stream.ThrowIfNull("stream"); fileRequest.ThrowIfNull("fileRequest") .Name.ThrowIfNullOrWhiteSpace("filedRequest.Name"); fileRequest.Parent.ThrowIfNull("fileRequest.Parent") .Id.ThrowIfNullOrWhiteSpace("fileRequest.Parent.Id"); BoxMultiPartRequest request = new BoxMultiPartRequest(_config.FilesUploadEndpointUri) { Timeout = timeout } .Param(ParamFields, fields) .FormPart(new BoxStringFormPart() { Name = "metadata", Value = _converter.Serialize(fileRequest) }) .FormPart(new BoxFileFormPart() { Name = "file", Value = stream, FileName = fileRequest.Name }); IBoxResponse <BoxCollection <BoxFile> > response = await ToResponseAsync <BoxCollection <BoxFile> >(request).ConfigureAwait(false); // We can only upload one file at a time, so return the first entry return(response.ResponseObject.Entries.FirstOrDefault()); }
private HttpRequestMessage BuildMultiPartRequest(BoxMultiPartRequest request) { HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post, request.AbsoluteUri); MultipartFormDataContent multiPart = new MultipartFormDataContent(); // Break out the form parts from the request var filePart = request.Parts.Where(p => p.GetType() == typeof(BoxFileFormPart)) .Select(p => p as BoxFileFormPart) .FirstOrDefault(); // Only single file upload is supported at this time var stringParts = request.Parts.Where(p => p.GetType() == typeof(BoxStringFormPart)) .Select(p => p as BoxStringFormPart); // Create the string parts foreach (var sp in stringParts) { multiPart.Add(new StringContent(sp.Value), ForceQuotesOnParam(sp.Name)); } // Create the file part if (filePart != null) { StreamContent fileContent = new StreamContent(filePart.Value); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = ForceQuotesOnParam(filePart.Name), FileName = ForceQuotesOnParam(filePart.FileName) }; multiPart.Add(fileContent); } httpRequest.Content = multiPart; return(httpRequest); }
/// <summary> /// Uploads a provided file to the target parent folder. /// If the file already exists, an error will be thrown. /// A proper timeout should be provided for large uploads. /// </summary> /// <param name="fileRequest">BoxFileRequest object.</param> /// <param name="stream">Stream of uploading file.</param> /// <param name="fields">Fields which shall be returned in result.</param> /// <param name="timeout">Timeout for response.</param> /// <param name="contentMD5">The SHA1 hash of the file.</param> /// <param name="setStreamPositionToZero">Set position for input stream to 0.</param> /// <param name="uploadUri">Uri to use for upload. Default upload endpoint URI is used if not specified.</param> /// <returns>A full file object is returned inside of a collection if the ID is valid and if the update is successful.</returns> public async Task <BoxFile> UploadAsync(BoxFileRequest fileRequest, Stream stream, List <string> fields = null, TimeSpan?timeout = null, byte[] contentMD5 = null, bool setStreamPositionToZero = true, Uri uploadUri = null) { stream.ThrowIfNull("stream"); fileRequest.ThrowIfNull("fileRequest") .Name.ThrowIfNullOrWhiteSpace("filedRequest.Name"); fileRequest.Parent.ThrowIfNull("fileRequest.Parent") .Id.ThrowIfNullOrWhiteSpace("fileRequest.Parent.Id"); if (setStreamPositionToZero) { stream.Position = 0; } uploadUri = uploadUri == null ? _config.FilesUploadEndpointUri : uploadUri; BoxMultiPartRequest request = new BoxMultiPartRequest(uploadUri) { Timeout = timeout } .Param(ParamFields, fields) .FormPart(new BoxStringFormPart() { Name = "attributes", Value = _converter.Serialize(fileRequest) }) .FormPart(new BoxFileFormPart() { Name = "file", Value = stream, FileName = fileRequest.Name }); if (contentMD5 != null) { request.Header(Constants.RequestParameters.ContentMD5, HexStringFromBytes(contentMD5)); } IBoxResponse <BoxCollection <BoxFile> > response = await ToResponseAsync <BoxCollection <BoxFile> >(request).ConfigureAwait(false); // We can only upload one file at a time, so return the first entry return(response.ResponseObject.Entries.FirstOrDefault()); }
/// <summary> /// This method is used to upload a new version of an existing file in a user’s account. Similar to regular file uploads, /// these are performed as multipart form uploads An optional If-Match header can be included to ensure that client only /// overwrites the file if it knows about the latest version. The filename on Box will remain the same as the previous version. /// </summary> /// <param name="fileName"></param> /// <param name="stream"></param> /// <param name="etag"></param> /// <returns></returns> public async Task <BoxFile> UploadNewVersionAsync(string fileName, string fileId, Stream stream, string etag = null, List <string> fields = null) { stream.ThrowIfNull("stream"); fileName.ThrowIfNullOrWhiteSpace("fileName"); BoxMultiPartRequest request = new BoxMultiPartRequest(new Uri(string.Format(Constants.FilesNewVersionEndpointString, fileId))) .Header("If-Match", etag) .Param(ParamFields, fields) .FormPart(new BoxFileFormPart() { Name = "filename", Value = stream, FileName = fileName }); IBoxResponse <BoxCollection <BoxFile> > response = await ToResponseAsync <BoxCollection <BoxFile> >(request).ConfigureAwait(false); // We can only upload one file at a time, so return the first entry return(response.ResponseObject.Entries.FirstOrDefault()); }
/// <summary> /// This method is used to upload a new version of an existing file in a user’s account. Similar to regular file uploads, /// these are performed as multipart form uploads. An optional If-Match header can be included to ensure that client only /// overwrites the file if it knows about the latest version. The filename on Box will remain the same as the previous version. /// To update the file’s name, you can specify a new name for the file using the fileName parameter. /// A proper timeout should be provided for large uploads. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="fileId">Id of the file to upload a new version to.</param> /// <param name="stream">Stream of the uploading file.</param> /// <param name="etag">This ‘etag’ field of the file, which will be set in the If-Match header.</param> /// <param name="fields">Fields which shall be returned in result.</param> /// <param name="timeout">Optional timeout for response.</param> /// <param name="contentMD5">The SHA1 hash of the file.</param> /// <param name="setStreamPositionToZero">Set position for input stream to 0.</param> /// <param name="uploadUri">Optional url for uploading file.</param> /// <returns>A full file object is returned.</returns> public async Task <BoxFile> UploadNewVersionAsync(string fileName, string fileId, Stream stream, string etag = null, List <string> fields = null, TimeSpan?timeout = null, byte[] contentMD5 = null, bool setStreamPositionToZero = true, Uri uploadUri = null) { fileName.ThrowIfNullOrWhiteSpace("fileName"); fileId.ThrowIfNullOrWhiteSpace("fileId"); stream.ThrowIfNull("stream"); if (setStreamPositionToZero) { stream.Position = 0; } uploadUri = uploadUri == null ? new Uri(string.Format(Constants.FilesNewVersionEndpointString, fileId)) : uploadUri; BoxMultiPartRequest request = new BoxMultiPartRequest(uploadUri) { Timeout = timeout } .Header(Constants.RequestParameters.IfMatch, etag) .Param(ParamFields, fields) .FormPart(new BoxFileFormPart() { Name = "filename", Value = stream, FileName = fileName }); if (contentMD5 != null) { request.Header(Constants.RequestParameters.ContentMD5, HexStringFromBytes(contentMD5)); } IBoxResponse <BoxCollection <BoxFile> > response = await ToResponseAsync <BoxCollection <BoxFile> >(request).ConfigureAwait(false); // We can only upload one file at a time, so return the first entry return(response.ResponseObject.Entries.FirstOrDefault()); }
/// <summary> /// Uploads a provided file to the target parent folder /// If the file already exists, an error will be thrown /// </summary> /// <param name="fileRequest"></param> /// <param name="stream"></param> /// <returns></returns> public async Task<BoxFile> UploadAsync(BoxFileRequest fileRequest, Stream stream, List<string> fields = null) { stream.ThrowIfNull("stream"); fileRequest.ThrowIfNull("fileRequest") .Name.ThrowIfNullOrWhiteSpace("filedRequest.Name"); fileRequest.Parent.ThrowIfNull("fileRequest.Parent") .Id.ThrowIfNullOrWhiteSpace("fileRequest.Parent.Id"); BoxMultiPartRequest request = new BoxMultiPartRequest(_config.FilesUploadEndpointUri) .Param(ParamFields, fields) .FormPart(new BoxStringFormPart() { Name = "metadata", Value = _converter.Serialize(fileRequest) }) .FormPart(new BoxFileFormPart() { Name = "file", Value = stream, FileName = fileRequest.Name }); IBoxResponse<BoxCollection<BoxFile>> response = await ToResponseAsync<BoxCollection<BoxFile>>(request).ConfigureAwait(false); // We can only upload one file at a time, so return the first entry return response.ResponseObject.Entries.FirstOrDefault(); }
/// <summary> /// This method is used to upload a new version of an existing file in a user’s account. Similar to regular file uploads, /// these are performed as multipart form uploads An optional If-Match header can be included to ensure that client only /// overwrites the file if it knows about the latest version. The filename on Box will remain the same as the previous version. /// </summary> /// <param name="fileName"></param> /// <param name="stream"></param> /// <param name="etag"></param> /// <returns></returns> public async Task<BoxFile> UploadNewVersionAsync(string fileName, string fileId, Stream stream, string etag = null, List<string> fields = null) { stream.ThrowIfNull("stream"); fileName.ThrowIfNullOrWhiteSpace("fileName"); BoxMultiPartRequest request = new BoxMultiPartRequest(new Uri(string.Format(Constants.FilesNewVersionEndpointString, fileId))) .Header("If-Match", etag) .Param(ParamFields, fields) .FormPart(new BoxFileFormPart() { Name = "filename", Value = stream, FileName = fileName }); IBoxResponse<BoxCollection<BoxFile>> response = await ToResponseAsync<BoxCollection<BoxFile>>(request).ConfigureAwait(false); // We can only upload one file at a time, so return the first entry return response.ResponseObject.Entries.FirstOrDefault(); }
public async Task UploadFile_ValidResponse_ValidFile() { /*** Arrange ***/ string responseString = "{ \"total_count\": 1, \"entries\": [ { \"type\": \"file\", \"id\": \"5000948880\", \"sequence_id\": \"3\", \"etag\": \"3\", \"sha1\": \"134b65991ed521fcfe4724b7d814ab8ded5185dc\", \"name\": \"tigers.jpeg\", \"description\": \"a picture of tigers\", \"size\": 629644, \"path_collection\": { \"total_count\": 2, \"entries\": [ { \"type\": \"folder\", \"id\": \"0\", \"sequence_id\": null, \"etag\": null, \"name\": \"All Files\" }, { \"type\": \"folder\", \"id\": \"11446498\", \"sequence_id\": \"1\", \"etag\": \"1\", \"name\": \"Pictures\" } ] }, \"created_at\": \"2012-12-12T10:55:30-08:00\", \"modified_at\": \"2012-12-12T11:04:26-08:00\", \"trashed_at\": null, \"purged_at\": null, \"content_created_at\": \"2013-02-04T16:57:52-08:00\", \"content_modified_at\": \"2013-02-04T16:57:52-08:00\", \"created_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"modified_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"owned_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"shared_link\": null, \"parent\": { \"type\": \"folder\", \"id\": \"11446498\", \"sequence_id\": \"1\", \"etag\": \"1\", \"name\": \"Pictures\" }, \"item_status\": \"active\", \"tags\": [ \"important\", \"needs review\" ] } ] }"; BoxMultiPartRequest boxRequest = null; _handler.Setup(h => h.ExecuteAsync <BoxCollection <BoxFile> >(It.IsAny <IBoxRequest>())) .Returns(Task.FromResult <IBoxResponse <BoxCollection <BoxFile> > >(new BoxResponse <BoxCollection <BoxFile> >() { Status = ResponseStatus.Success, ContentString = responseString })) .Callback <IBoxRequest>(r => boxRequest = r as BoxMultiPartRequest); var createdAt = new DateTime(2016, 8, 27); var modifiedAt = new DateTime(2016, 8, 28); var fakeFileRequest = new BoxFileRequest() { Name = "test.txt", ContentCreatedAt = createdAt, ContentModifiedAt = modifiedAt, Parent = new BoxRequestEntity() { Id = "0" } }; var createdAtString = createdAt.ToString("yyyy-MM-ddTHH:mm:sszzz"); var modifiedAtString = modifiedAt.ToString("yyyy-MM-ddTHH:mm:sszzz"); var fakeStream = new Mock <System.IO.Stream>(); /*** Act ***/ BoxFile f = await _filesManager.UploadAsync(fakeFileRequest, fakeStream.Object, null, null, new byte[] { 0, 1, 2, 3, 4 }); /*** Assert ***/ Assert.IsNotNull(boxRequest); Assert.AreEqual(RequestMethod.Post, boxRequest.Method); Assert.AreEqual(_FilesUploadUri, boxRequest.AbsoluteUri.AbsoluteUri); Assert.AreEqual(2, boxRequest.Parts.Count); Assert.AreEqual("attributes", boxRequest.Parts[0].Name); Assert.IsNotNull(boxRequest.Parts[0] as BoxStringFormPart); Assert.IsTrue(AreJsonStringsEqual( "{\"content_created_at\":\"" + createdAtString + "\",\"content_modified_at\":\"" + modifiedAtString + "\",\"parent\":{\"id\":\"0\"},\"name\":\"test.txt\"}", (boxRequest.Parts[0] as BoxStringFormPart).Value)); Assert.AreEqual("file", boxRequest.Parts[1].Name); Assert.IsNotNull(boxRequest.Parts[1] as BoxFileFormPart); Assert.AreEqual("test.txt", (boxRequest.Parts[1] as BoxFileFormPart).FileName); Assert.IsTrue(object.ReferenceEquals(fakeStream.Object, (boxRequest.Parts[1] as BoxFileFormPart).Value)); Assert.IsTrue(boxRequest.HttpHeaders.ContainsKey("Content-MD5")); Assert.AreEqual(HexStringFromBytes(new byte[] { 0, 1, 2, 3, 4 }), boxRequest.HttpHeaders["Content-MD5"]); Assert.AreEqual("5000948880", f.Id); Assert.AreEqual("3", f.SequenceId); Assert.AreEqual("tigers.jpeg", f.Name); Assert.AreEqual("134b65991ed521fcfe4724b7d814ab8ded5185dc", f.Sha1); Assert.AreEqual(629644, f.Size); Assert.AreEqual("important", f.Tags[0]); Assert.AreEqual("needs review", f.Tags[1]); }
/// <summary> /// This method is used to upload a new version of an existing file in a user’s account. Similar to regular file uploads, /// these are performed as multipart form uploads. An optional If-Match header can be included to ensure that client only /// overwrites the file if it knows about the latest version. The filename on Box will remain the same as the previous version. /// To update the file’s name, you can specify a new name for the file using the fileName parameter. /// A proper timeout should be provided for large uploads. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="fileId">Id of the file to upload a new version to.</param> /// <param name="stream">Stream of the uploading file.</param> /// <param name="etag">This ‘etag’ field of the file, which will be set in the If-Match header.</param> /// <param name="fields">Fields which shall be returned in result.</param> /// <param name="timeout">Optional timeout for response.</param> /// <param name="contentMD5">The SHA1 hash of the file.</param> /// <param name="setStreamPositionToZero">Set position for input stream to 0.</param> /// <param name="uploadUri">Optional url for uploading file.</param> /// <returns>A full file object is returned.</returns> public async Task<BoxFile> UploadNewVersionAsync(string fileName, string fileId, Stream stream, string etag = null, List<string> fields = null, TimeSpan? timeout = null, byte[] contentMD5 = null, bool setStreamPositionToZero = true, Uri uploadUri = null) { fileName.ThrowIfNullOrWhiteSpace("fileName"); fileId.ThrowIfNullOrWhiteSpace("fileId"); stream.ThrowIfNull("stream"); if (setStreamPositionToZero) stream.Position = 0; uploadUri = uploadUri == null ? new Uri(string.Format(Constants.FilesNewVersionEndpointString, fileId)) : uploadUri; BoxMultiPartRequest request = new BoxMultiPartRequest(uploadUri) { Timeout = timeout } .Header(Constants.RequestParameters.IfMatch, etag) .Param(ParamFields, fields) .FormPart(new BoxFileFormPart() { Name = "filename", Value = stream, FileName = fileName }); if (contentMD5 != null) request.Header(Constants.RequestParameters.ContentMD5, HexStringFromBytes(contentMD5)); IBoxResponse<BoxCollection<BoxFile>> response = await ToResponseAsync<BoxCollection<BoxFile>>(request).ConfigureAwait(false); // We can only upload one file at a time, so return the first entry return response.ResponseObject.Entries.FirstOrDefault(); }
/// <summary> /// Uploads a provided file to the target parent folder. /// If the file already exists, an error will be thrown. /// A proper timeout should be provided for large uploads. /// </summary> /// <param name="fileRequest">BoxFileRequest object.</param> /// <param name="stream">Stream of uploading file.</param> /// <param name="fields">Fields which shall be returned in result.</param> /// <param name="timeout">Timeout for response.</param> /// <param name="contentMD5">The SHA1 hash of the file.</param> /// <param name="setStreamPositionToZero">Set position for input stream to 0.</param> /// <param name="uploadUri">Uri to use for upload. Default upload endpoint URI is used if not specified.</param> /// <returns>A full file object is returned inside of a collection if the ID is valid and if the update is successful.</returns> public async Task<BoxFile> UploadAsync(BoxFileRequest fileRequest, Stream stream, List<string> fields = null, TimeSpan? timeout = null, byte[] contentMD5 = null, bool setStreamPositionToZero = true, Uri uploadUri = null) { stream.ThrowIfNull("stream"); fileRequest.ThrowIfNull("fileRequest") .Name.ThrowIfNullOrWhiteSpace("filedRequest.Name"); fileRequest.Parent.ThrowIfNull("fileRequest.Parent") .Id.ThrowIfNullOrWhiteSpace("fileRequest.Parent.Id"); if (setStreamPositionToZero) stream.Position = 0; uploadUri = uploadUri == null ? _config.FilesUploadEndpointUri : uploadUri; BoxMultiPartRequest request = new BoxMultiPartRequest(uploadUri) { Timeout = timeout } .Param(ParamFields, fields) .FormPart(new BoxStringFormPart() { Name = "attributes", Value = _converter.Serialize(fileRequest) }) .FormPart(new BoxFileFormPart() { Name = "file", Value = stream, FileName = fileRequest.Name }); if (contentMD5 != null) request.Header(Constants.RequestParameters.ContentMD5, HexStringFromBytes(contentMD5)); IBoxResponse<BoxCollection<BoxFile>> response = await ToResponseAsync<BoxCollection<BoxFile>>(request).ConfigureAwait(false); // We can only upload one file at a time, so return the first entry return response.ResponseObject.Entries.FirstOrDefault(); }