Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

Sagar Malde 5 Reputation points
2024-05-07T09:36:03.3533333+00:00

Hi,

I am getting an error as Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) while uploading a file in Document library via webpart by JSOM.

Below is the Code that I am using to upload file in chunks.

that.insertDocument = function (file, Id, docType, resolutionId, TicketNumber, handleLoader = true) {

// Generate a new GUID string

var newGuid = SP.Guid.newGuid().toString();

console.log(newGuid);

// Function to create a GUID string in the correct format

function createGuid() {

return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxx'.replace(/[xy]/g, function (c) {

var r = Math.random() * 16 | 0,

v = c == 'x' ? r : (r & 0x3 | 0x8);

return v.toString(16);

});

}

// Get the context and the SharePoint list where you want to upload the file

var clientContext = SP.ClientContext.get_current();

var web = clientContext.get_web();

clientContext.load(web, 'ServerRelativeUrl');

clientContext.executeQueryAsync(

async function () {

console.log

var folderServerRelativeUrl = web.get_serverRelativeUrl() + '/ArcilDocuments';

var docLib = web.getFolderByServerRelativeUrl(folderServerRelativeUrl);

console.log(folderServerRelativeUrl);

var chunkSize = 1024 * 1024;

//var fileInput = document.getElementById('fileInput');

//var file = fileInput.files[0];

//debugger

// Calculate the number of chunks

var fileSize = file.size;

var numChunks = Math.ceil(fileSize / chunkSize);

var fileName = file.name;

var names = fileName.split('.');

var ext = names.pop();

var newName = TicketNumber.replace(/\//g, '-') + '-' + names[0] + '-' + new Date().getTime() + '.' + ext;

console.log(newName);

// Create a new file creation information object

var fileCreateInfo = new SP.FileCreationInformation();

console.log("fileCreateInfo object:", fileCreateInfo);

fileCreateInfo.set_url(newName);

console.log("fileCreateInfo after set_url():", fileCreateInfo);

fileCreateInfo.set_overwrite(true);

console.log("fileCreateInfo after set_overwrite():", fileCreateInfo);

fileCreateInfo.set_content(new SP.Base64EncodedByteArray());

console.log("fileCreateInfo after set_content():", fileCreateInfo);

console.log(fileCreateInfo);

//debugger

// Upload the file to SharePoint

var newFile = docLib.get_files().add(fileCreateInfo);

var listItem = newFile.get_listItemAllFields();

listItem.set_item('Year', new Date().getFullYear());

listItem.set_item('TicketId', Id);

listItem.set_item('DocumentType', docType);

listItem.set_item('UploadedOn', new Date());

listItem.set_item('ResolutionId', resolutionId);

listItem.set_item('DocumentStatus', true);

listItem.update();

// Upload the file in chunks

var chunkIndex = 0;

var offset = 0;

var chunkReader = new FileReader();

chunkReader.onload = async function (evt) {

if (evt.target.error == null) {

var buffer = evt.target.result;

var endpoint = offset + buffer.byteLength - 1;

var chunkStream = new SP.Base64EncodedByteArray();

chunkStream.append(buffer);

var parameters = new SP.FileCreationInformation();

parameters.ContentStream = chunkStream;

parameters.FileName = newName;

parameters.Offset = offset;

parameters.OverwriteIfExists = true;

//debugger

// Start uploading the chunk

if (chunkIndex == 0) {

console.log(newGuid);

console.log("parameters object:", parameters);

// Start uploading the chunk

newFile.startUpload(parameters, newGuid);

console.log('Upload start');

} else {

//var chunkStream = new SP. Base64EncodedByteArray();

//chunkStream.append(buffer);

newFile.continueUpload(chunkStream);

console.log('upload continuously')

}

// Move to the next chunk or finish uploading

chunkIndex++;

offset += chunkSize;

if (offset < fileSize) {

readNextChunk();

} else {

newFile.finishUpload();

console.log('Upload completed');

clientContext.load(newFile);

await clientContext.executeQueryAsync(

function () {

var fileUrl = uploadedFile.get_serverRelativeUrl();

if (handleLoader == true) {

commonHelper.showHideLoader(false);

}

//console.log('File uploaded successfully - ' + fileUrl);

deferred.resolve(fileUrl);

},

function (sender, args) {

if (handleLoader == true) {

commonHelper.showHideLoader(false);

}

console.log('Error uploading file: ' + args.get_message());

deferred.resolve('');

}

);

}

}

}

var readNextChunk = function () {

var start = offset;

var end = Math.min(start + chunkSize, fileSize);

chunkReader.readAsArrayBuffer(file.slice(start, end));

};

readNextChunk();

})

};

SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
10,808 questions
JavaScript API
JavaScript API
An Office service that supports add-ins to interact with objects in Office client applications.
996 questions
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
3,032 questions
{count} votes

2 answers

Sort by: Most helpful
  1. RaytheonXie_MSFT 36,091 Reputation points Microsoft Vendor
    2024-05-08T06:09:06.82+00:00

    Hi @Sagar Malde,This error message shows you create a wrong Guid format. You could use following code to create a 32 digits with 4 dashes guid

    // Define a function named 'guid' that generates a unique identifier.
    function guid(len) {
        // Initialize an empty array to store characters of the generated identifier.
        var buf = [],
            // Define a string containing all possible characters for the identifier.
            chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
            // Calculate the length of the character string.
            charlen = chars.length,
            // Set the desired length of the identifier or default to 32.
            length = len || 32;
        // Loop 'length' times to generate the identifier.
        for (var i = 0; i < length; i++) {
            // Generate a random index to pick a character from the character string.
            buf[i] = chars.charAt(Math.floor(Math.random() * charlen));
        }
        // Return the generated identifier by joining the array of characters into a string.
    	var code = buf.join('');
    	var fCode = code.substring(0, 8) + "-" + code.substring(8, 12) + "-" + code.substring(12, 16) 		+ "-" + code.substring(16, 20) + "-" + code.substring(20);
    
    	return fCode;
    }
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. RaytheonXie_MSFT 36,091 Reputation points Microsoft Vendor
    2024-05-21T01:33:31.8166667+00:00

    Hi @Sagar Malde

    I'm glad to hear you solve the problem ,if you have any issue about SharePoint, you are welcome to raise a ticket in this forum.

    By the way, since the Microsoft Q&A community has a policy that "The question author cannot accept their own answer. They can only accept answers by others." and according to the scenario introduced here: Answering your own questions on Microsoft Q&A, I would make a brief summary of this thread:

    [Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)]

    Issue Symptom:

    Getting an error as Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) while uploading a file in Document library via webpart by JSOM.

    Solution:

    Passed the parameters incorrect. The startUpload method expects the first parameter to be GUID. The correct way of calling method should be newFile.startUpload(newGuid, offset, chunkStream);


    You could click the "Accept Answer" button for this summary to close this thread, and this can make it easier for other community member's to see the useful information when reading this thread. Thanks for your understanding!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.