2

Using this link - Convert event.target.files into a JSON string I was able to get the file data. I form a JSON with like - {'fileName':xyz.jpeg,'file': <fileContent>} and pass it to an Apex Controller. I used below code to insert the file ( using ContentVersion metadata ) like below (https://www.salesforcecodecrack.com/2019/06/custom-file-upload-in-lightning-web.html)

    String fileData = EncodingUtil.urlDecode((String)data.get('file'), 'UTF-8');
    // inserting file
    ContentVersion cv = new ContentVersion();
    cv.Title = (String)data.get('fileName');
    cv.PathOnClient = '/' + data.get('fileName');
    cv.FirstPublishLocationId = '0033h0000054rJVAAY'; // A contact record Id to test
    cv.VersionData = EncodingUtil.base64Decode(fileData);
    cv.IsMajorVersion = true;
    insert cv;

contentVersion is inserted successfully and I was able to download the image. However the image is not clear and look like it has been distorted. How do I store the original version of the file.

enter image description here

9
  • have you considered using a multipart upload? it appears to me like the file may have only partially when in
    – Ronnie
    Apr 12, 2020 at 19:46
  • How could i confirm if the file have only partially when in. May be i could debug based on that?
    – SfdcBat
    Apr 12, 2020 at 19:54
  • what is the size of the file listed on the ContentDocument in the ContentSize field and how does it compare to the actual file you dropped in?
    – Ronnie
    Apr 12, 2020 at 19:55
  • original file is 8 KB and in the debug logs I see (9273946)|VARIABLE_ASSIGNMENT|[19]|this.VersionData|BLOB(8268 bytes)|0x4150d8d
    – SfdcBat
    Apr 12, 2020 at 19:58
  • 1
    Thanks. I had to not use this - EncodingUtil.urlDecode((String)data.get('file'), 'UTF-8'); instead just get (String)data.get('file') and decode it and it worked.
    – SfdcBat
    Apr 12, 2020 at 20:39

1 Answer 1

2
`EncodingUtil.urlDecode((String)data.get('file'), 'UTF-8')` 

wasn't necessary. decoding just this (String)data.get('file') was the right way.

3
  • just remember, if you're not encoding, you should never have to decode it (assuming you're controlling the content and it is not downloaded as base64)
    – Ronnie
    Apr 13, 2020 at 0:04
  • Got it. Actually its result of File ReaderAsDataURL which always return base64encoded string
    – SfdcBat
    Apr 13, 2020 at 0:14
  • 1
    developer.mozilla.org/en-US/docs/Web/API/FileReader/… Maybe that Note attached here may be part of it.
    – Ronnie
    Apr 13, 2020 at 0:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .