Laravel 9 can not handle request content return 403 - request

When you send entries in Arabic, some of them cause a problem
like:
var data = new FormData();
data.append('name', ' ليبغاثقبسالثفقال');
var data = new FormData();
data.append('name', ' تجريبي');
The above works fine.
data.append('name', ' ليبغاثقبسالثفقال');
But this does not work. Something is a problem with Arabic encode.

Related

Cannot upload a file in blob in sharefile

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?

Netsuite webservices upload and get url in C#

When I upload file I get internalId as response.
My requirement is to get fileURL.
Eg: to get internalId ((RecordRef)(writeRes.baseRef)).internalId))
Is there any way to get fileURL after uploading?
You need to send a new request to get the file once it's uploaded:
var internalId = ((RecordRef)(writeRes.baseRef)).internalId));
RecordRef file = new RecordRef();
recordRef.internalId = internalId;
recordRef.type = RecordType.file;
recordRef.typeSpecified = true;
ReadResponse response = service.get(recordRef);
File file = (File)(response.record);
var fileUrl = file.url;

How to display images in web page using angularjs?

I already know how to save images in mongodb using angularjs and java to save it in my mongodb,
I need to get the saved image from mongodb and display it in an html page using AngularJS.
This is my controller for getting image
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getById(#PathParam("id") String id) throws IOException
{
Response response = null;
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB mongoDB = mongoClient.getDB("sampleDB");
DBCollection collection = mongoDB.getCollection("filestore");
BasicDBObject query = new BasicDBObject();
ObjectId oid = new ObjectId(id);
query.put("_id", oid);
GridFS fileStore = new GridFS(mongoDB, "filestore");
GridFSDBFile gridFile = fileStore.findOne(query);
InputStream in = gridFile.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int data = in.read();
while (data >= 0)
{
out.write((char) data);
data = in.read();
}
out.flush();
ResponseBuilder builder = Response.ok(out.toByteArray());
builder.header("Content-Disposition", "attachment; filename=");
response = builder.build();
return response;
}
This is my angularjs for getting image
var userImagePromise = $http.get("../api/s3/" + $scope.user.profileImage[0].id);
userImagePromise.success(function(data, status, headers, config) {
$scope.imageData = data;
});
userImagePromise.error(function(data, status, headers, config) {
});
This is my html for displaying image
<img id="userProfileImg" height="150px" width="150px" ng-src="data:image/png;base64,{{imageData}}">
if I simply put the link to browser i got this output in octect-stream
�PNG .....
How to display image in html?Any error in my code wise?
Image for getting output
i think your base64 code is not converting images properly, so check my code it may help you.
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
BufferedImage buffimage = ImageIO.read(new File(imagePath));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(buffimage, "png", baos);
String img = Base64.encode(baos.toByteArray());
send this img variable to your angularjs code.

node js post file to php api on remote server

I have to post a file to a php api url on a remote server.
I am creating a http.request and then trying to write file data to this request by piping it from filestream as below :
var req = http.request( options, function(response) {
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
var fs = require('fs');
var boundaryKey = "5JtsIWpXzRoEIdPqkQiSWv4Tl8Bmq";//Math.random().toString(16); // random string
var filelen = filelen; \\Already calculated before
req.setHeader('Content-Type', 'multipart/form-data;boundary='+boundaryKey);
req.setHeader('Content-Length', filelen);
// the header for the one and only part (need to use CRLF here)
req.write('--' + boundaryKey + '\r\n'
// "name" is the name of the form field
// "filename" is the name of the original file
+ 'Content-Disposition: form-data; name="gamefile"; filename="image.jpg"\r\n'
// use your file's mime type here, if known
+ 'Content-Type: image/jpeg\r\n'
+ 'Content-Transfer-Encoding: binary_file_data\r\n\r\n'
);
var fileStream = fs.createReadStream('/image.jpg');
fileStream.pipe(req, { end: false }); // maybe write directly to the socket here?
fileStream.on('end', function() {
console.log("File Streamed");
// mark the end of the one and only part
req.end('--' + boundaryKey + '--\r\n\r\n');
});
On my php server what I get in files array :
Array
(
[gamefile] => Array
(
[name] => image.jpg
[type] =>
[tmp_name] =>
[error] => 3
[size] => 0
)
)
which means that my file is not reaching the server.
Please suggest if i am doing something wrong or do need to do something else.
Take a look at the Request module. It makes doing REST requests really easy including doing a POST request with a file included. Take a look at the Forms documentation for more information. Basically it's something like:
var request = require('request');
var r = request.post('http://service.com/upload')
var form = r.form()
form.append('my_field', 'my_value')
form.append('my_buffer', new Buffer([1, 2, 3]))
form.append('my_file', fs.createReadStream(path.join(__dirname, 'doodle.png'))
form.append('remote_file', request('http://google.com/doodle.png'))

using HTTPRequest setPayload in google app engine

I am trying to do HTTPRequest Post via Google App Engine.
This is what I have so far
URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(########);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
Here I need to put some paired values (ie. "email","hi#example.com" etc)
Since setPayload accept byte[] I have no idea how to convert my paired values
into byte.
I have searched other posts but I am very stuck.
EDIT:
I have changed to this but it is still not working
byte[] data = ("EMAIL=bo0#gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000;").getBytes();
try {
URL url = new URL("http://www.bo.x10.mx/nPost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
This is what I have on php website.
<?php
include "path/conf.php"; //logging into database works
$tb_name = 'Post';
$EMAIL=$_POST['EMAIL'];
$TITLE =$_POST['TITLE'];
$COMMENT =$_POST['COMMENT'];
$PRICE =$_POST['PRICE'];
if(!isset($EMAIL) || !isset($TITLE ) || !isset($PRICE )|| !isset($COMMENT)){
header('HTTP/1.0 412 Precondition Failed', true, 412);
die('Bad data');
}
$sql="INSERT INTO $tb_name(EMAIL, TITLE, COMMENT, PRICE) VALUES ('$EMAIL', '$TITLE ', '$COMMENT ', '$PRICE ')";
$result=mysql_query($sql);
if($result==TRUE){
echo "successfully inserted into table!";}
else{
echo "error in inserting into table!";
header('HTTP/1.0 500 Internal Server Error', true, 500);}
ob_end_flush();
exit();
?>
EDIT2: This is a working code
try{
byte[] data = ("EMAIL=bo0#gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000").getBytes("UTF-8");
URL url = new URL("http://www.box.com/nost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
}
My database string field is of type UTF-8
You create a String with the request body, and then you get the byte array. For example we have:
URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
String body = "email=" + email + "&mpla=" + mpla;
request.setPayload(body.getBytes("UTF-8"));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
Hope this helps!

Resources