SAPUI5: FileUploader Not Working - file-upload

I am using sap.ui.unified.FileUploader for uploading file. I am also adding slug and X-CSRF-Token with in header.But i am unable to send header values to gateway, means in gateway side csrf token value is blank.I tested with Rest Client its working fine
code:
View
<u:FileUploader
id="fileUploader1"
name="myFileUpload"
mimeType ="image,text"
uploadUrl=""
uploadOnChange="false"
width="400px"
tooltip="Upload your file to the local server"
uploadComplete="handleUploadComplete" />
<Button
text="Upload File"
press="handleUploadPress" />
Controller
handleUploadPress: function (oEvent) {
var url = "http://xxxxx.xxxx.xxxx:1234/sap/opu/odata/sap/ZGW_GC1_SRV/GCUpload1Set";
var oFileUploader = this.getView().byId("fileUploader1");
oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
name: "slug",
value: oFileUploader.getValue()
}));
oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
name: "x-csrf-token",
value: oController.oModel.getSecurityToken()
}));
oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
name: "sendXHR",
value: true
}));
oFileUploader.setUploadUrl(url);

The attribute "sendXHR" has to be set at the FileUploader instance, not as header parameter. Then it should work.
oFileUploader.setSendXHR(true);

Related

When trying to download certain video it redirects to a new URL and the video starts to play. "disposable content type" is not received from server

I want to download certain videos with a click. For that, I created a Button and attached a Function that should trigger the associated video download.
But I am only able to download the link of the video, not the video. I am able to download videos with an external downloader or simply drag the URL to the download section of the browser. But unable to trigger that activity via JavaScript. Please help Me.
I tried multiple ways to tackle this problem:
Using a Simple Blob Technique without Axios:
const blob = new Blob([this.src_url], { type: 'video/mp4' })
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = this.src_url.replace(
>! // 'https://redis-test.com/videos/',
link.click()
URL.revokeObjectURL(link.href)
endpoint: video URL get downloaded as a file of 122 bytes
Then using File Saver Package:
var FileSaver = require('file-saver')
console.log(this.src_url)
var blob = new Blob([this.src_url], { type: 'video/mp4' })
FileSaver.saveAs(blob, 'hello world.mp4')
Then using the form method:
<form method="get" action="file.doc">
<button type="submit">Download!</button>
</form>
endpoint: video starts to play in the same window
Using href download attribute:
function download(url) {
const a = document.createElement('a')
a.href = url
a.download = url.split('/').pop()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
endpoint: video starts to play in the same window
Using your method:
const link = document.createElement('a')
link.href = url
link.click()
endpoint: video starts to play in the same windows
With Axios defaults now:
axios.defaults.withCredentials = true
window.open(
'https://cdn.pixaandom_urlrbay.com/vieo/487508532/Woman%20-%2058142.mp4?rendition=source&expiry=1666842719&hash=7dd6d178d9dbbd8adaf68dafd80c9167e91eca21&download'
)
endpoint: video starts to play in the new window
With attaching disposable content type in headers with AXIOS:
axios
.get(
String(nuxtConfig.axios.mediaURL) +
this.src_url.replace(
'https://redisrandom_url.com/videos/',
''
),
{
headers: {
mode: 'no-cors',
referrerPolicy: 'no-referrer',
'Content-Disposition': 'attachment; filename=Woman - 58142.mp4',
Host: 'redis-nfs',
'User-Agent': 'PostmanRuntime/7.29.2',
Accept: '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
Connection: 'keep-alive',
Cookie:
'tk_or=%22https%3A%2F%2Fwww.google.com%2F%22; tk_lr=%22https%3A%2F%2Fwww.google.com%2F%22; _gcl_au=1.1.954672920.1660108804; _ga=GA1.2.1392122600.1660108808; _fbp=fb.1.1660108809200.1970395787',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
Pragma: 'no-cache',
'Cache-Control': 'no-cache',
},
}
)
.then((response) => {
console.log(response)
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'title')
document.body.appendChild(link)
link.click()
})
.catch((error) => {
console.log('rex')
})
endpoint: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at redis-random_url/videos/be319-72e1-2e79-8dc3-bcef1/…. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200
"...But I am only able to download the link of the video, not the video."
I don't use VueJS but I suspect this.src_url is just text of the path to video URL.
In HTML5 you can only download those files that exist on your server. If the file is external then you need a PHP script (on same server as your HTML file) to read those external bytes back into your JS buffer array.
const blob = new Blob([this.src_url], { type: 'video/mp4' })
Should be:
let myBytes = //# update variable with data result of reading files bytes
let myBlob = new Blob( [ Uint8Array.from( myBytes ) ] , {type: "application/octet-stream"} );
Where the bytes reading can be done with FileReader API or Fetch API.
When you can read a file's bytes into an Array using VueJS then your problem is solved.

Cloud Flare, R2, how to upload images?

Cloud Flare, R2, how to upload images??
I`m new to Cloud Flare world,
and I can upload the pictures by dragging but
how to upload image using coding? from application??
do I have to use "WORKERS" <-- things?
I have uploaded files to r2 successfully with rclone.
Configure rclone
First, install rclone on our PC.
And then create a rclone.conf file under the path ~/.config/rclone/.
[r2]
type = s3
provider = Cloudflare
access_key_id = <ACCESS_KEY>
secret_access_key = <SECRET_ACCESS_KEY>
region = auto
endpoint = https://<ACCOUNT_ID>.r2.cloudflarestorage.com
acl = private
[r2]: A custom name(an alias) for storage service. We need to use it to operate files.
type = s3: The type of file operation API. R2 supports the S3 standard protocol.
provider = Cloudflare: The storage provider ID. You could use man rclone to get the supported providers.
access_key_id: You need to create a token with edit permission on the R2 console.
secret_access_key: Same as above.
endpoint: The url that rclone uses to operate files. To get the account id on the top-right of R2 homepage.
Usage
run rclone lsf r2: to see your buckets and rclone lsf r2:my-bucket to show the file list within a bucket.
Especially notice the last symbol :
upload a file:
rclone copy /path/to/file r2:my-bucket
Hey I got stuck with this for two days and was not able to figure it out. So I wanted to share my solution.
My Goal
I was developing a software for collecting data from our end users to get information from them. But they needed an image to be submitted for us to verify them, that is why I needed to have a form to enable users to upload their file and an API endpoint to store their file.
Solution
I set up an Cloudflare worker as an API since it connects well with R2, you just have to define it in your worker settings.
My Cloudflare worker script & Example form for allowing users to upload files
// CLOUDFLARE WORKER SCRIPT
// ------------------------
export default {
async fetch(request, env) {
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, HEAD, POST, OPTIONS',
'Access-Control-Max-Age': '86400',
};
// Check for preflight request from the browser.
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: {
...corsHeaders,
'Access-Control-Allow-Headers': request.headers.get(
'Access-Control-Request-Headers'
),
}
});
} else {
// Handle actual request and store image to bucket.
const { headers } = request;
// Key is date now since we want keys to be unique.
const key = Date.now();
await env.MY_BUCKET.put(key, request.body, {
httpMetadata: {
contentType: headers.get('content-type')
}
});
return new Response('success!', {
headers: {
...corsHeaders,
'Access-Control-Allow-Headers': request.headers.get(
'Access-Control-Request-Headers'
),
}
});
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Upload Images with Cloudflare R2</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data">
<label for="image">Select image to upload:</label>
<input type="file" name="image" id="image" /><br /><br />
<input type="submit" value="Upload" />
</form>
<script>
async function uploadImage(file) {
fetch('https://<YOUR-OWN-WORKER>.workers.dev', {
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': file.type
},
body: file
})
.then((response) => response.text())
.then((data) => console.log(data))
.catch((error) => console.error(error));
}
const image = document.getElementById('image');
const onSelectFile = () => uploadImage(image.files[0]);
image.addEventListener('change', onSelectFile, false);
</script>
</body>
</html>

NestJS Upload multiple files with dto

I'm trying to upload files with dto object, but got error:
[Nest] 8296 - 11/29/2021, 1:05:08 AM [ExceptionsHandler] request entity too large +378162ms
PayloadTooLargeError: request entity too large
Here is my code:
#Post()
#UseInterceptors(
FileFieldsInterceptor([
{ name: 'picture', maxCount: 1 },
{ name: 'audio', maxCount: 1 },
]),
)
create(#UploadedFiles() files, #Body() dto: CreateTrackDto) {
console.log('files', files);
return this.trackService.create(dto, '', '');
}
I've tried to upload files without dto object and it works fine, but when I added the second param as dto object from the body I got this.
Actually tried set limits for uploaded files in main.ts file like this:
// app.use(json({ limit: '50mb' }));
// app.use(urlencoded({ extended: true, limit: '50mb' }));
and set limits in FileFieldsInterceptor in localOptions object
but got the same error.
Does anyone know how to fix it?
"#nestjs/common": "^7.6.15",
"#nestjs/core": "^7.6.15",
"#nestjs/mongoose": "^9.0.1",
"#nestjs/platform-express": "^7.6.15"
"#types/multer": "^1.4.7"
windows 10

Using Temporary Credentials giving SignatureDoesNotMatch issue

We are working on s3 browser based multipart file using EvaporateJS, Using pre-signed URL with temperory credentials.
Following will be my configuration
var amz_headers_common = {};
var amz_headers_at_initiate = {};
var amz_headers_at_upload = {};
var amz_headers_at_complete = {};
amz_headers_common['x-amz-acl'] = 'private';
amz_headers_common['x-amz-security-token'] = '<?=AWS_TOKEN;?>';
amz_headers_at_initiate['x-amz-acl'] = 'private';
amz_headers_at_initiate['x-amz-security-token'] = '<?=AWS_TOKEN;?>';
var customAuth = $("#signingMethod")[0].checked;
Evaporate.create({
signerUrl: customAuth ? undefined : '<?=AWS_SIGNER_URL;?>',
aws_key: '<?=AWS_KEY;?>' ,
bucket: '<?=AWS_S3_BUCKET;?>',
cloudfront: false,
computeContentMd5: true,
cryptoMd5Method: function (data) { return AWS.util.crypto.md5(data, 'base64'); },
cryptoHexEncodedHash256: function (data) { return AWS.util.crypto.sha256(data, 'hex'); },
logging: true,
s3Acceleration: true,
signTimeout: 10,
s3FileCacheHoursAgo: 1,
maxConcurrentParts:5,
allowS3ExistenceOptimization: true,
sendCanonicalRequestToSignerUrl: true,
customAuthMethod: customAuth? doNotUseUnsafeJavaScriptV4Signer : undefined,
evaporateChanged: function (file, evaporatingCount) {
$('#totalParts').text(evaporatingCount);
if (evaporatingCount > 0) {
$("#pause-all, #pause-all-force, #cancel-all").show();
} else if (evaporatingCount === 0) {
$("#pause-all, #pause-all-force, #resume, #cancel-all").hide();
}
}
})
var promise = _e_.add({
name: name,
file: files[i],
started: callback_methods.started,
complete: callback_methods.complete,
cancelled: callback_methods.cancelled,
progress: callback_methods.progress,
error: callback_methods.error,
warn: callback_methods.warn,
paused: callback_methods.paused,
pausing: callback_methods.pausing,
resumed: callback_methods.resumed,
nameChanged: callback_methods.nameChanged,
xAmzHeadersCommon: amz_headers_common,
xAmzHeadersAtInitiate: amz_headers_at_initiate,
xAmzHeadersAtUpload: amz_headers_at_upload,
xAmzHeadersAtComplete: amz_headers_at_complete
},
{
bucket: '<?=AWS_S3_BUCKET;?>', // Shows that the bucket can be changed per
aws_key: '<?=AWS_KEY;?>' // Shows that aws_key can be changed per
}
But I'm getting following signature mismatch error.
AWS Code: SignatureDoesNotMatch, Message:The request signature we calculated does not match the signature you provided. Check your key and signing method.status:403
Following will be log
Without temperary credentials following cannonical request and v4 string to sign.
POST
/test-video.mp474.6796611212833
uploads=
host:<bucket-name>.s3-accelerate.amazonaws.com
x-amz-date:20170428T055938Z
host;x-amz-date
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
V4 stringToSign: AWS4-HMAC-SHA256
20170428T055938Z
20170428/ap-southeast-1/s3/aws4_request
ce2c7c5fbbf58483efbd4bd244551d138353ebb7b7233d3fdce73e85d96fad8d
--------------------------------------------------------------------------------------
Using temperary credentials following cannonical request and v4 string to sign.
initiate V4 CanonicalRequest: POST
/test-video.mp461.80892198840156
uploads=
host:<bucket-name>.s3-accelerate.amazonaws.com
x-amz-acl:private
x-amz-date:20170427T160400Z
x-amz-security-token:FQoDYXdzEDEaDIkS6zY1Oj8PQLLDVSK5A5pPusfWw81Yq3v0c4VqlyyQsBDW+PHosDuDnG8EYc9jlXD1tQwiTKU1E2Nf3aKcYmv/BHYwGwOen9GPStPeVBGbWNBzi1lT+B6xOnDvIXzelnuC6Eddt+jYIrjy9RVIKBN/s80NtVwfjmFK+93iOWJzdl2ruRSzQINZ+UuSmuthudkYLZzKy0pDmCrgIz8YCjXsjhN7FyeSZzXk9qmBDCASygVEFDNbkb/xidH/Yj7P9gYdsxY6YokV/CM8ZpAKmE8Lp+en+xs9rDclexFzCId8QyJaGj0xb205WoeRIHr8RSStvyounCxrmhWP6M/eijWTP/uHIfWVDqBadEPSgVWqcEzrW2iJ+0SGROb+In6BMmkEMaw+9L5M+lkgCfMDm5Fw9Ip8bujcb4okoNjEn6L+L0b1lm3yuqvLkT3oOzL3Sn48n3y0dXsYtt3yAq+C02bnfmgtYVQgv1C9TaMHrvipFADYNJ9U81HxQWlgvuSG5BEgqV59PIzGhwPFHais/GyA+a1bmxkyhzKEw1yq6F6+wQ+VBRskmPlahQd9ZK3wrnqvpQm+H7tD2YLkVVQb+AGKtRVU3mOL3yjgnYjIBQ==
host;x-amz-acl;x-amz-date;x-amz-security-token
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
V4 stringToSign: AWS4-HMAC-SHA256
20170427T160400Z
20170427/ap-southeast-1/s3/aws4_request
e0b18a695b23bc16b6727fd2dc417e445266111ebb4995794287a46304d2cc92
Please help me to solve singature mismatch issue.
Wherever you instantiate your S3 client for the bucket, you'll want to set your signature version to v4, since that's what your temporary credentials are configured for. Something like this:
var s3 = new AWS.S3({
signatureVersion: 'v4'
});

angular fullstack generator can not send iamge stored in mongodb

What a want to achieve is simple. I am using angular fullstack generator to produce the skeleton. User should be able to upload a profile picture along with their name, email etc. I am using angular-file-uplpoad to send the multipart form request. And according to its wiki, I also used code below.
// Requires multiparty
multiparty = require('connect-multiparty'),
multipartyMiddleware = multiparty(),
// Requires controller
UserController = require('./controllers/UserController');
// Example endpoint
router.post('/api/user/uploads', multipartyMiddleware, UserController.uploadFile);
I am also using gridfs-stream to stream the profile image into mongo gridfs. Everything seems fine here. Because if I stream the profile image into server local file, I can actually open and view the image. The problem is that, now I want to send the image back to the browser. I wrote code below
var Grid = require('gridfs-stream');
var GridFS = Grid(mongoose.connection.db, mongoose.mongo);
var fs = require('fs');
/*
var UserSchema = new Schema({
first_name: String,
last_name: String,
email: { type: String, lowercase: true },
role: {
type: String,
default: 'user'
},
hashedPassword: String,
provider: String,
salt: String,
phone: String,
projects: [{
type : Schema.Types.ObjectId,
ref : 'Project'
}],
profile_picture: Schema.Types.ObjectId
});
*/
// each user has a _id for a image file in mongodb
getFile : function() {
var readstream = GridFS.createReadStream({
_id : this.profile_picture,
});
response.writeHead(200, {'Content-Type': 'iamge/png' });
readstream.pipe(response);
},
But this does not work. To test it. I even use fs.createReadStream(filename) to load a static image stored in the server side. The image is actually sent but the it's a broken image received in the browser. I also tried response.download('filename'); still does not work. Any suggestions?
Thanks!
You wrote: {'Content-Type': 'iamge/png' }
Fix it to: {'Content-Type': 'image/png' }
Let me know if that solves it because I am also having problems and have similar code.