maximum file upload size in sharepoint - sharepoint

I use the following method to upload a document into sharepoint document library.
However, upon executing the query - get the following error:
Message = "The remote server returned an error: (400) Bad Request."
the files are failing over 1mb, so i tested it via the sharepoint UI and the same file uploaded successfully.
any thoughts on what's the issue is? is it possible to stream the file over rather than 1 large file chunk? the file in question is only 3mb in size..
private ListItem UploadDocumentToSharePoint(RequestedDocumentFileInfo requestedDoc, ClientContext clientContext)
{
try
{
var uploadLocation = string.Format("{0}{1}/{2}", SiteUrl, Helpers.ListNames.RequestedDocuments,
Path.GetFileName(requestedDoc.DocumentWithFilePath));
//Get Document List
var documentslist = clientContext.Web.Lists.GetByTitle(Helpers.ListNames.RequestedDocuments);
var fileCreationInformation = new FileCreationInformation
{
Content = requestedDoc.ByteArray,
Overwrite = true,
Url = uploadLocation //Upload URL,
};
var uploadFile = documentslist.RootFolder.Files.Add(fileCreationInformation);
clientContext.Load(uploadFile);
clientContext.ExecuteQuery();
var item = uploadFile.ListItemAllFields;
item["Title"] = requestedDoc.FileNameParts.FileSubject;
item["FileLeafRef"] = requestedDoc.SharepointFileName;
item.Update();
}
catch (Exception exception)
{
throw new ApplicationException(exception.Message);
}
return GetDocument(requestedDoc.SharepointFileName + "." + requestedDoc.FileNameParts.Extention, clientContext);
}
EDIT: i did find the following ms page regarding my issue (which seems identical to the issue they have raised) http://support.microsoft.com/kb/2529243 but appears to not provide a solution.

ok found the solution here:
http://blogs.msdn.com/b/sridhara/archive/2010/03/12/uploading-files-using-client-object-model-in-sharepoint-2010.aspx
i'll need to store the document on the server hosting the file then using the filestream upload process i've done in my code below:
private ListItem UploadDocumentToSharePoint(RequestedDocumentFileInfo requestedDoc, ClientContext clientContext)
{
try
{
using(var fs = new FileStream(string.Format(#"C:\[myfilepath]\{0}", Path.GetFileName(requestedDoc.DocumentWithFilePath)), FileMode.Open))
{
File.SaveBinaryDirect(clientContext, string.Format("/{0}/{1}", Helpers.ListNames.RequestedDocuments, requestedDoc.FileName), fs, true);
}
}
catch (Exception exception)
{
throw new ApplicationException(exception.Message);
}
return GetDocument(requestedDoc.SharepointFileName + "." + requestedDoc.FileNameParts.Extention, clientContext);
}

Related

Authentication Failure when uploading to Azure Blob Storage using Azure.Storage.Blob v12.9.0

I get this error when trying to upload files to blob storage. The error is present both when I run on localhost and when I run in Azure Function.
My connection string looks like:
DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxx;EndpointSuffix=core.windows.net
Authentication information is not given in the correct format. Check the value of the Authorization header.
Time:2021-10-14T15:56:26.7659660Z
Status: 400 (Authentication information is not given in the correct format. Check the value of Authorization header.)
ErrorCode: InvalidAuthenticationInfo
But this used to work in the past but recently its started throwing this error for a new storage account I created. My code looks like below
public AzureStorageService(IOptions<AzureStorageSettings> options)
{
_connectionString = options.Value.ConnectionString;
_containerName = options.Value.ImageContainer;
_sasCredential = new StorageSharedKeyCredential(options.Value.AccountName, options.Value.Key);
_blobServiceClient = new BlobServiceClient(new BlobServiceClient(_connectionString).Uri, _sasCredential);
_containerClient = _blobServiceClient.GetBlobContainerClient(_containerName);
}
public async Task<string> UploadFileAsync(IFormFile file, string location, bool publicAccess = true)
{
try
{
await _containerClient.CreateIfNotExistsAsync(publicAccess
? PublicAccessType.Blob
: PublicAccessType.None);
var blobClient = _containerClient.GetBlobClient(location);
await using var fileStream = file.OpenReadStream();
// throws Exception here
await blobClient.UploadAsync(fileStream, true);
return blobClient.Uri.ToString();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
// To be able to do this, I have to create the container client via the blobService client which was created along with the SharedStorageKeyCredential
public Uri GetSasContainerUri()
{
if (_containerClient.CanGenerateSasUri)
{
// Create a SAS token that's valid for one hour.
var sasBuilder = new BlobSasBuilder()
{
BlobContainerName = _containerClient.Name,
Resource = "c"
};
sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
sasBuilder.SetPermissions(BlobContainerSasPermissions.Write);
var sasUri = _containerClient.GenerateSasUri(sasBuilder);
Console.WriteLine("SAS URI for blob container is: {0}", sasUri);
Console.WriteLine();
return sasUri;
}
else
{
Console.WriteLine(#"BlobContainerClient must be authorized with Shared Key
credentials to create a service SAS.");
return null;
}
}
Please change the following line of code:
_blobServiceClient = new BlobServiceClient(new BlobServiceClient(_connectionString).Uri, _sasCredential);
to
_blobServiceClient = new BlobServiceClient(_connectionString);
Considering your connection string has all the necessary information, you don't really need to do all the things you're doing and you will be using BlobServiceClient(String) constructor which expects and accepts the connection string.
You can also delete the following line of code:
_sasCredential = new StorageSharedKeyCredential(options.Value.AccountName, options.Value.Key);
and can probably get rid of AccountName and Key from your configuration settings if they are not used elsewhere.

Getting CustomerVisionErrorException: Operation returned an invalid status code "BadRequest"

Im trying to use Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction feature by submitting an image by using pickphoto cross media and geting a result of a predicition. I have tried to pass the image as url or a stream and keep getting a badrequest. I know that I have the correct prediction key and endpoint because i works for training telling me is the way I pass the image into the method. What is the correct way to transform the image from Cross Media pick photo package into the
private async void UplodatePictureButton_Clicked(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
MediaFile file;
if (!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("No upload", "Picking a photo is not supported", "OK");
return;
}
file = await CrossMedia.Current.PickPhotoAsync();
if (file == null)
{
return;
}
MainImage.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
return stream;
});
// Create the Api, passing in the training key
CustomVisionTrainingClient trainingApi = new CustomVisionTrainingClient()
{
ApiKey = trainingKey,
Endpoint = SouthCentralUsEndpointTraining
};
var projects = trainingApi.GetProjects();
var project = projects.FirstOrDefault(p => p.Name == "Car");
CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient()
{
ApiKey = predictionKey,
Endpoint = SouthCentralUsEndpointPrediction
};
var result = endpoint.ClassifyImageUrl(project.Id, project.Name, new Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction.Models.ImageUrl(file.Path));
foreach (var c in result.Predictions)
{
Console.WriteLine($"\t{c.TagName}: {c.Probability:P1}");
}
}
Unhandled Exception:
Microsoft.Azure.CognitiveService.Vision.CustomerVision.Prediction.Models.CustomVisionErrorException: Operation returned an invalid status code "BadRequest"
Expect a prediction.
Here is the picture of the code:
code
Here is the picture of the problem:
problem
I got the same "Bad Request Message" while trying to do a endpoint.DetectImage(projectId, iteractionName, stream). The thing is that last week it was working Perfect. I have noticed that it only happens with large images arround 2 mb

OneDrive Copy Item using Microsoft Graph SDK - GatewayTimeout at 10 seconds if ~>38mb file

I am using the MS Graph .net SDK. Attempting to copy a sharepoint document library to another sharepoint document library.
If the file is approximately 38mb, a GatewayTimeout exception is thrown for an unknown error.
Either MS has a bug, or I am doing something incorrectly. Here is my code:
HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Post, request.RequestUrl);
hrm.Content = new StringContent(JsonConvert.SerializeObject(request.RequestBody), System.Text.Encoding.UTF8, "application/json");
await client.AuthenticationProvider.AuthenticateRequestAsync(hrm);
HttpResponseMessage response = await client.HttpProvider.SendAsync(hrm);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
}
}
catch (Microsoft.Graph.ServiceException ex)
{
throw new Exception("Unknown Error");
}
Anyone see a problem here?
EDIT: Here is my revised code
public static async Task copyFile(Microsoft.Graph.GraphServiceClient client, string SourceDriveId, string SourceItemId, string DestinationDriveId, string DestinationFolderId, string FileName)
{
try
{
var destRef = new Microsoft.Graph.ItemReference()
{
DriveId = DestinationDriveId,
Id = DestinationFolderId
};
await client.Drives[SourceDriveId].Items[SourceItemId].Copy(null, destRef).Request().PostAsync();
//await client.Drives[SourceDriveId].Root.ItemWithPath(itemFileName).Copy(parentReference: dest).Request().PostAsync();
}
catch (Microsoft.Graph.ServiceException ex)
{
throw new Exception(ex.Message);
}
}
The above revised code continues to give the same error; however, tonight, it is also occurring on a 13.8mb file that previously had worked fine.
Logically, because the error doesn't occur for smaller files, I think it has something to do with file size.
The response is supposed to be a 202 with location header. See Copy Item in Graph Docs; however, I have never been able to obtain a location header. I suspect that Microsoft Graph is not getting the location header information from the OneDrive API and is therefore throwing a Gateway Timeout error.
I believe this is what you're looking for:
await graphClient.Drives["sourceDriveId"]
.Items["sourceItemId"]
.Copy(null, new ItemReference()
{
DriveId = "destinationDriveId",
Id = "destinationFolderId"
})
.Request()
.PostAsync();
This will take a given DriveItem and copy it to a folder in another Drive.

Using HttpClient to upload files to ServiceStack server

I can't use the ServiceStack Client libraries and I've chosen to use the HttpClient PCL library instead. I can do all my Rest calls (and other json calls) without a problem, but I'm now stucked with uploading files.
A snippet of what I am trying to do:
var message = new HttpRequestMessage(restRequest.Method, restRequest.GetResourceUri(BaseUrl));
var content = new MultipartFormDataContent();
foreach (var file in files)
{
byte[] data;
bool success = CxFileStorage.TryReadBinaryFile(file, out data);
if (success)
{
var byteContent = new ByteArrayContent(data);
byteContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = System.IO.Path.GetFileName(file) ,
};
content.Add(byteContent);
}
}
message.Content = content;
Problem is now that I get a null reference exception (status 500) when posting. I doesn't get into the service. I see the call in the filterrequest, but that's it.
So I'm wondering what I do wrong and how I can pinpoint what is going wrong. How can I catch the correct error on the ServiceStack layer?

Uploading file in sharepoint library throws an unhandled exception(hresult: 0x80020009, errorcode: -2147352567) with empty error message

I m using following code sample to upload multiple files (using sharepoint Object Model, no webservice) in a document library, but some times it throws exception hresult: 0x80020009, with error code -2147352567 and error message is empty (empty string) while file is upload successfully to the document library. And mostly it occurs only first time mean it occurs when uploading first document after that all process goes smoothly no exception occurs after first time occured. If i eat that exception it works fine. Can any one help me to trace the problem, I can't understand why it throws exception while file has been uploaded to document library. I want to know What's the actual reason and what should I do to avoid that problem.
Code:
.....
SPFolder folder = web.GetFolder(folderUrl);
foreach(.....)
{
folder.Files.Add(folderUrl + "/" + fileName, file.Data, true);
}
try using the code provided below that will help you out
using (SPSite spsite = new SPSite("http://SPS01"))
{
using (SPWeb spweb = spsite.OpenWeb())
{
spweb.AllowUnsafeUpdates = true;
SPFolder spfolder = spweb.Folders[Site + "/Shared Documents/"];
byte[] content = null;
using (FileStream filestream = new FileStream("C:/Sample.docx", System.IO.FileMode.Open))
{
content = new byte[(int)filestream.Length];
filestream.Read(content, 0, (int)filestream.Length);
filestream.Close();
}
SPFile spfile = spfolder.Files.Add("Sample.docx", content, true);
//Upload file in subfolder.
//SPFile spfile = spfolder.SubFolders["Demonstration Folder"].Files.Add("Sample.docx", content, true);
spfile.Update();
}
}

Resources