You need to sign in to do that
Don't have an account?
miku
How to deal with 'BLOB is not a valid UTF-8 string' error
I write a apex class to import csv file from the VF page. The 'BLOB is not a valid UTF-8 string' raising.I don't how to set the csv encode. or is there any way to convert the file to UTF-8 by apex code.
Any suggestion would be appriciate.
Thanks.
Ok, I'm shooting in the dark but I assume your problem code looks smth like this:
You can't convert "BINARY" data into a String. A String only supports valid UTF-8 strings. Use EncodingUtil.Base64Encode if you need the binary data in a string you can work with.
Also check to see if your csv doesn't have some weird chars in it, I don't know like chinnese etc
EncodingUtil Class
All Answers
Ok, I'm shooting in the dark but I assume your problem code looks smth like this:
You can't convert "BINARY" data into a String. A String only supports valid UTF-8 strings. Use EncodingUtil.Base64Encode if you need the binary data in a string you can work with.
Also check to see if your csv doesn't have some weird chars in it, I don't know like chinnese etc
EncodingUtil Class
And if i have special character (french accent) to be written in a file and save as attachment.How do i encode the string , note that attachment body take blob contents ?
Got the answer by myself. In fact to encode an string in apex in UTF-8 to b inserted into a document body, i have done this :
Attachement a = new Attachment();
a.body = str;
a.ContentType = 'text/plain; charset=UTF-8';
a.parent = parentId;
insert a;
Special characters are considere.
Cool!
I've looked for a solution but I've missed the ContentType.
Great find @vanessen.
I have created CSV using apex with special character. If I download the CSV file from object it will opened correctly in CSV editor. But it had junk value in Excel. What is the problem with that. I have changed utf-8 in Excel also. But Still i have the same problem.
public string nameFile{get; set;}
public Blob contentFile{get; set;}
nameFile=contentFile.toString();
https://www.codengine.in/2019/06/blob-is-not-a-valid-utf-8-string-salesforce-apex.html
public static String blobToString(Blob input, String inCharset){
String hex = EncodingUtil.convertToHex(input);
System.assertEquals(0, hex.length() & 1);
final Integer bytesCount = hex.length() >> 1;
String[] bytes = new String[bytesCount];
for(Integer i = 0; i < bytesCount; ++i)
bytes[i] = hex.mid(i << 1, 2);
return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
}
1. make sure you use the CSV (Comma delimited)(*.csv) format ONLY
2. confirm your csv file does not contain any special characters