I have example request:
curl https://upload.box.com/api/2.0/files/content \
-H "Authorization: Bearer ACCESS_TOKEN" \
-F filename=#FILE_NAME \
-F parent_id=PARENT_FOLDER_ID
My request returns an error missing_parameter","name":"parent","message":"'parent' is required".
This is my request:
String boundary = String.valueOf(DateTime.now().getTime());
String body = '------------' + boundary + '\r\n';
body +='Content-Disposition: form-data; name="FileName"; FileName="' + fileBody +'"\r\n';
body+='Content-Transfer-Encoding: base64\r\n';
if ((contentType == null) || (contentType == '')){contentType = 'application/octet-stream';}
body+='Content-Type: ' + contentType + '\r\n\r\n';
body+=EncodingUtil.base64Encode(fileBody);
body +='Content-Disposition: form-data; name="Parent"; \r\n';
body+='Content-Transfer-Encoding: base64\r\n';
if ((contentType == null) || (contentType == '')){contentType = 'application/octet-stream';}
body+='Content-Type: ' + contentType + '\r\n\r\n';
body+=0;
body+='\r\n------------' + boundary + '--';
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type', 'multipart/form-data; boundary=----------' + boundary);
req.setHeader('Content-Length',String.valueof(body.length()));
req.setBody(body);
req.setHeader('Authorization', 'Bearer ' + accessToken.token__c);
req.setMethod('POST');
req.setEndpoint('https://upload.box.com/api/2.0/files/content');
Http http = new Http();
HttpResponse res = http.send(req);
It's asking for the ID of the folder you want to upload to.
try changing this line:
body +='Content-Disposition: form-data; name="Parent"; \r\n';
to:
body +='Content-Disposition: form-data; name="parent_id"; \r\n';
EDIT: though I have to ask, why are you sending the whole file body as the file name?
Related
public with sharing class uploadFileToGdrive {
public static void fileUploadHandler(List<ContentVersion> cvFileList) {
for (ContentVersion cvFile : cvFileList) {
system.debug('Loop');
// Get the content of the document
ContentVersion contentVersion = [SELECT Title, VersionData, FileType FROM ContentVersion WHERE ContentDocumentId = :cvFile.contentDocumentId ORDER BY CreatedDate DESC LIMIT 1];
Blob fileBody = contentVersion.VersionData;
String fileName = contentVersion.Title;
String fileType = contentVersion.FileType;
String boundary = '-------'+contentVersion.Id;
String header = 'Content-Type: multipart/related; boundary="' + boundary + '"\n' +
'Authorization: Bearer ' + [SELECT Access_Token__c FROM gDriveTokens__c][0].Access_Token__c + '\n' +
'Content-Length: ' + String.valueOf(fileBody.size()) + '\n' +
'\n';
String body = '--' + boundary + '\n' +
'Content-Type: application/json; charset=UTF-8\n' +
'\n' +
'{"name": "' + fileName + '"}\n' +
'--' + boundary + '\n' +
'Content-Type: '+MIMEHelper.getMIMEType(fileType)+'\n' +
'\n';
String requestBody = header + body + EncodingUtil.base64Encode(fileBody) + '\n--' + boundary + '--';
uploadFileToGdrive.uploadFileCallout(requestBody, boundary);
}
}
#future(callout=true)
public static void uploadFileCallout(String requestBody, String boundary) {
system.debug('Callout');
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart');
req.setHeader('Content-Type', 'multipart/related; boundary="' + boundary + '"');
req.setheader('Authorization','Bearer '+[SELECT Access_Token__c FROM gDriveTokens__c][0].Access_Token__c);
req.setBody(requestBody);
// Send the request
Http http = new Http();
HttpResponse res = http.send(req);
system.debug(res.getBody());
}
}
I was trying to upload a file from my salesforce system to my google drive using google drive api. The files are uploading. But when I download or try to open them, it shows this message.
Drive File Error
I am trying to upload a file in Citrix ShareFile via REST API. There are four requests
Get the access_token
Get the folder URI's to decide n which I am going to upload the file.
Get chunk Uri
Upload the file in that chunk Uri
The first three steps work perfectly. When I am trying to POST a request for the no 4. part,
it is creating a file in sharefile but with size of 0.
I have tried that with POSTMAN, and with form-data and the selection of a file, it is working fine. The file is uploaded in sharefile.
The problem arises when I am trying to upload blob data.
I am calling this methods from Salesforce Platform and in Salesforce, I cannot get the physical file in a physical location. I have blob file data stored in salesforce database.
The below part works well.
String fileName_m = 'a12.pdf';
// Get Authentication Token
HttpRequest req = new HttpRequest();
req.setEndpoint('https://{server}.sf-api.com/oauth/token?grant_type=password&client_id={client_id}&client_secret={secret}&username={user_name}&password={password}!');
req.setMethod('GET');
Http http = new Http();
HttpResponse response = http.send(req);
System.Debug(response.getBody());
Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());
String token = '';
String refreshtoken = '';
if(response.getStatusCode() == 200){
token = (String)results.get('access_token');
refreshtoken = (String)results.get('refresh_token');
}
system.debug('token=' + token);
// Get Folder ID
HttpRequest req1 = new HttpRequest();
req1.setEndpoint('https://{server}.sf-api.com/sf/v3/Items?$expand=Children');
req1.setMethod('GET');
req1.setHeader('Authorization','Bearer ' + token);
Http http1 = new Http();
HttpResponse response1 = http1.send(req1);
System.Debug(response1.getBody());
Map<String, Object> results1 = (Map<String, Object>)JSON.deserializeUntyped(response1.getBody());
String url = '';
if(response1.getStatusCode() == 200){
url = (String)results1.get('url');
}
System.Debug('Folder Url ' + url);
// Get Chunk URI
HttpRequest req2 = new HttpRequest();
String endPoint = url + '/Upload2';
req2.setEndpoint(endPoint);
req2.setMethod('POST');
req2.setHeader('Authorization','Bearer ' + token);
req2.setHeader('Content-Type', 'application/x-www-form-urlencoded');
String payload1 = 'FileName='+fileName_m;
req2.setBody(payload1);
Http http2 = new Http();
HttpResponse response2 = http2.send(req2);
Map<String, Object> results2 = (Map<String, Object>)JSON.deserializeUntyped(response2.getBody());
String ChunkUri = '';
if(response2.getStatusCode() == 200){
ChunkUri = (String)results2.get('ChunkUri');
}
System.Debug('ChunkUri' + ChunkUri);
But, when I am trying to upload blob file data in sharefile, the API responds with a 200 status code. In sharefile, the file is created, but the size of the file is 0.
// Problem is here, it is not working
// Upload File
Attachment att = [SELECT Id, Body, Name, ContentType FROM Attachment WHERE Id='00P3p00001XNLOHEA5'];
String body = EncodingUtil.base64Encode(att.body);
List<Attachment> cvList = [SELECT Id, Body, Name, ContentType FROM Attachment WHERE Id='00P3p00001XNLOHEA5'];
String attachmentBody = EncodingUtil.base64Encode(cvList[0].Body);
Blob pdfBlob = EncodingUtil.base64Decode(attachmentBody);
system.debug('pdfBlob' + pdfBlob);
HttpRequest req3 = new HttpRequest();
req3.setEndpoint(ChunkUri);
req3.setMethod('POST');
req3.setHeader('Authorization','Bearer ' + token);
req3.setHeader('Content-Length', String.valueOf(attachmentBody.length()));
req3.setHeader('Content-Encoding', 'UTF-8');
req3.setHeader('Content-type', 'application/pdf');
req3.setHeader('Connection', 'keep-alive');
req3.setBodyAsBlob(pdfBlob);
Http http3 = new Http();
HttpResponse response3 = http3.send(req3);
System.Debug(response3.getBody());
How to solve the issue?
I am getting bad request error while trying to get token using this piece of code:
String clientId = '3MVG9t0sl2P.pByrrjfFFCVMbFHMMMm.qRQK6yRQw8Mg0rfs1s_.x2q1TuhonbyuxNJlugwGXKIvGmFEJ';
String clientSecret = '0ABB12793CB8CEB88DCFC9103DE2867A72642025E5F7DC40CB77B5A986404';
String username='mp7mp#gmail.com';//salesforce username
String password='Yg8#';//EUe4eHjMxXb8UFco1SPcpsZL9';//salesforce password
// Generating the Access Token
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('https://login.salesforce.com/services/oauth2/token');// this is the OAuth endpoint where this request will be hit
req.setBody('grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password);
Http http = new Http();
HTTPResponse response = http.send(req);
if(response.getStatusCode() == 200){
system.debug('## Successfully retrieving access token' );
map<string,Object> resultMap = (map<string,Object>)JSON.deserializeUntyped(response.getBody());
accesstoken = (String)resultMap.get('access_token');
instanceURL = (String)resultMap.get('instance_url');
system.debug('Accesstoken'+ accesstoken );
system.debug('instanceURL'+ instanceURL);
//step 2 : use the token for the salesforce api call
}
else{
system.debug('## Could not retrieve the access token' + response.getStatusCode() + '--'+ response.getStatus());
system.debug('## response status :' + response.getStatus());
system.debug('## response message :' + response.getBody());
}
This is the request:
grant_type=password&client_id=3MVG9t0sl2P.pByrrjfFFCm.qRQK6yo58pRQw8Mg0rfs1s_.x2q1TuhonbyuxNJlugwGXKIvGmFEJ&client_secret=0ABB12793738CEB88DCFC9103DE2867A72642025E5F7DC40CB77B5A986404&username=mp7504.mp#com&password=Ygua8#
I am trying to post an image form the cabinet to an API
the API is rejected call with Content-Type": "multipart/form-data:
{
httpCode: "405",
httpMessage: "Method Not Allowed",
message: "PUT, POST require an input body.",
errorClass: "Exception"
}
the API is rejected call without Content-Type": "multipart/form-data:
{
httpCode: "400",
httpMessage: "Bad Request",
message: "JSON Input was invalid. Error Message: Syntax error",
errorClass: "InvalidArgumentException"
}
the current code is:
function ItemImageCreation(){
var itemId = 4;
var payload;
var StringUrl = "https://someURL";
var boundary = '--' + uuidv4();
var files = file.load(1056); // getting the file
var fileContents = files.getContents(); // getting the content
var decodedStr = fromBaseUTF(fileContents); // conversion to Base64
var form_data = "{\"description\": \"Test Image\",\n\"ordering\": 1\n}";
// add the data field
payload = "\n" + boundary + "\n"
+ 'Content-Disposition: form-data; name=\"data\"\n\n'
+ form_data + "\n"
+ boundary + "\n"
+ 'Content-Disposition: form-data; name=\"image\"\n'
+ 'Content-Type: image/jpeg\n\n'
+ decodedStr + "\n"
+ boundary + "--\n\n";
log.debug("payload", payload);
var Header = {"Authorization": "Bearer " + token,
"Content-Type": "multipart/form-data; boundary=" + boundary
};
try {
var response = https.post({
url: StringUrl,
body: payload,
headers: Header
});
var newSFID = JSON.parse(response.body);
log.debug("Item Image creation", newSFID);
} catch (e) {
log.error({ title: 'Failed to submit file', details: (e.message || e.toString()) + (e.getStackTrace ? (' \n \n' + e.getStackTrace().join(' \n')) : '') });
log.error('ERROR Item Image Creation', JSON.stringify(e));
}
}
using postman, the image is correctly sent:
I am using a scheduled script, do you see what is wrong or is there a way to know what is send by netsuite?
There is an answer here that covers this: In NetSuite with SuiteScript 2.0 unable to send a file with HTTP POST request with a content-type multipart/form-data
what you missing is the Content-Transfer-Encoding header and you should be getting the content as Base64 so you shouldn't need to convert from UTF16 ( I could be wrong on that but I've never needed to)
When i am trying to upload files in Box Storage using api provided by Box but at response time i am getting this error
public static void UploadFileRequest(string FolderID, string accesstoken)
{
string boundary = string.Format("----------------------------{0}", DateTime.Now.Ticks.ToString("x"));
string filename="C:\\Users\\Administrator\\Desktop\\Text.txt";
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("https://upload.box.com/api/2.0/files/content");
ASCIIEncoding encoding = new ASCIIEncoding();
string hh = "\"filename=#\"" + filename + "\" "+";"+"";
hh += "parent_id=\"" + FolderID + "\"";
string kj = string.Format(("filename=#" + filename));
byte[] data = encoding.GetBytes(hh);
httpWReq.Headers.Add("Authorization", "Bearer " + accesstoken);
httpWReq.ContentType = "application/json";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
Without knowing the Box API, I will assume that the upload should be a POST operation, so you will need to specify the correct HTTP method on your request, before sending it:
httpWReq.Method = "POST";
The Method property defaults to "GET", and GET operations does not normally have a body..
Here is the solution , as C# accepts bytes format and then any Upload is done , i was missing that .. hope it helps
private void UploadBoxFile(string Filename)
{
HttpWebRequest req = HttpWebRequest.Create("https://upload.box.com/api/2.0/files/content") as HttpWebRequest;
req.Method = "POST";
req.Headers.Add("Authorization", "Bearer < Access Token >");
req.ContentType = "multipart/form-data; boundary=\"d174f29b-6def-47db-8519-3da38b21b398\"";
string Content = GetFormatedData(Filename);
req.ContentLength = Content.Length;
using (Stream Writer = req.GetRequestStream())
{
Writer.Write(Encoding.UTF8.GetBytes(Content), 0, Content.Length);
}
req.GetResponse();
}
private string GetFormatedData(string Filename)
{
StringBuilder build = new StringBuilder();
string Id = "d174f29b-6def-47db-8519-3da38b21b398";
build.AppendLine("--" + Id);
build.AppendLine("Content-Disposition: form-data; filename=\"hello1.txt\"; name=\"filename\"");
build.AppendLine("Content-Type: application/octet-stream");
build.AppendLine();
string FileContent = "This is a sample text";
build.AppendLine(FileContent);
build.AppendLine("--" + Id);
build.AppendLine("Content-Disposition: form-data; name=\"folder_id\"");
build.AppendLine();
build.AppendLine("0");
build.AppendLine("--" + Id + "--");
return build.ToString();
}
Thanks..