I have the following:
new qq.FileUploader({
element: $('#' + domid + ' #upload')[0],
action: '/api/panel/upload_file',
debug: true,
allowedExtensions: [
'jpg',
'jpeg',
'gif',
'png',
'bmp',
'pdf'
],
params: {
room : 'a_room',
module : 'a_module'
},
onSubmit: function(id, fileName) {
this.params.name = fileName;
},
onProgress: function(id, fileName, loaded, total) { },
onComplete : function(id, fileName, data) {
/* FINISH */
}
});
Which sends the upload request to:
case "api" :: "panel" :: "upload_file" :: Nil Post req => {
var response = true
req.body match {
case Full(file) =>
/* DO SOMETHING */
case _ => response = false
}
}
This works fine in both Firefox and Chrome, but when uploading with IE9 the file doesnt seem to get past:
req.body match {
case Full(file) =>
}
Is there something I'm missing or need to do to get this working properly?
Thanks in advance for any help, much appreciated :)
Firstly, req.body will give you an array of bytes, not a file. Lift will automatically detect if you're uploading a file or an arbitrary payload. Its not a good idea to put files into memory, especially if they might be large.
Look into req.uploadedFiles, and req.rawInputStream with OnDiskFileParamHolder.apply - if i recall how vallums uploader works, you have to manually push the input stream into the FileParamHolder, from which you can just call .file and then have a direct java.io.File instance to work with.
Related
I’m using FilePond 4.30.4 with React and react-filepond 7.1.2. Everything is working great and I can upload files.
My server responds with a file ID, and this comes back down to FilePond. I can see it in the onprocessfile event.
I’d like to include this is the ‘Upload Complete’ message. e.g. ‘Complete, file 12345’. How can I set this?
I’ve tried to update .labelFileProcessingComplete in onprocessfile, but it has no effect. I can see my events being fired and the correct data in the console. Perhaps there is another way to update the 'Upload Complete' label with a custom message for the file.
<FilePond
ref={filePondRef}
oninit={() => handleInit()}
files={files}
onupdatefiles={setFiles}
onprocessfile={ (error, file) => {
if (error) {
console.log('OnProcessFile: we have an error:' + error);
console.dir(error);
return;
}
console.log('OnProcessFile:File processed', file);
console.log('OnProcessFile:set processed message to ', file.serverId);
//This has no effect
filePondRef.current.labelFileProcessingComplete='Completed:-#' + file.serverId;
}
}
labelIdle='Drag & Drop your files or <span class="filepond--label-action">Browse</span>'
server={ {
timeout: 7000,
process: {
url: apiUrl,
method: 'POST',
withCredentials: false,
timeout: 7000,
onload: (res) => {
console.log('onload:and label with res=' + res);
// this has no effect either
filePondRef.current.labelFileProcessingComplete='Completed:' + res;
return res;
}
}
}
}
labelFileProcessingError= {() => {
// replaces the error on the FilePond error label
console.log('labelFileProcessingError: serverResponse is:' + serverResponse );
return serverResponse;
}}
/>
Below is my code in cypress. How to print 'pdf' content and verify content using cypress .contains or .eq? when I run the code it prints object{6} but I want to print my pdf file content. I would really appreciate the help.
**Plugins/index.js:**
const fs = require('fs')
const pdf = require('pdf-parse')
const path = require('path')
const repoRoot = path.join("C:/Users/XXXXX/Downloads/loginCy-excel")
const parsePdf = async (pdfName) => {
const pdfPathname = path.join(repoRoot, pdfName)
let dataBuffer = fs.readFileSync(pdfPathname);
return await pdf(dataBuffer)
}
module.exports = (on, config) => {
on('task', {
getPdfContent (pdfName) {
return parsePdf(pdfName)
},
})
}
**cypress spec file has these code:**
it('tests a pdf', () => {
cy.task('getPdfContent', 'sample.pdf').then(content => {
cy.log(content)
})
})
pdf method will return an object, so I guess cy.log() can't print it like that. If you want to see what the function gathered in your pdf file, you can stringify the result:
cy
.log(JSON.stringify(content));
If you want to get only text from your pdf, you need to work with text property:
cy
.log(content.text);
Anyone struggling with testing PDF files with cypress can refer to these two very good blog posts precisely on this topic:
https://filiphric.com/testing-pdf-file-with-cypress
https://glebbahmutov.com/blog/cypress-pdf/
It wasn't asked in this question, but here is a little addition from me on how to download files (was tested on PDFs) from a URL:
cy.request({
url: '<file url>',
gzip: false,
encoding: 'base64',
}).then((response) => {
cy.writeFile(
Cypress.config('downloadsFolder') + '/<name of the file>.pdf',
response.body,
{ encoding: 'base64' }
);
First of all, this is the start of where I am at as a similar post
Store blob as a file in S3 with Laravel
I am sending a photo from VueJS to Laravel. It is coming as multipart/form-data.
Vue Code:
export default {
emits: ['onClose'],
props: ['isOpen'],
data: function() {
return {
serverOptions: {
process: (fieldName, file, metadata, load, error) => {
const formData = new FormData();
formData.append(fieldName, file, file.name);
axios({
method: "POST",
url: '/chat/room/upload',
data: formData,
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(() => {
load();
})
.catch(() => {
error();
});
}
},
files: [],
};
},
methods: {
handleFilePondInit: function () {
console.log('FilePond has initialized');
// example of instance method call on pond reference
this.$refs.pond.getFiles();
console.log(this.$refs.pond.getFiles());
},
},
Laravel Controller:
public function uploadImage(Request $request)
{
// This is what this is SUPPOSED to do. Grab the file from the frontend
// Bring it here. Store it in S3, return the path with the CDN URL
// Then store that URL into the DB as a message. Once that is done, then
// Broadcast the message to said room.
if ($request->has('upload')) {
$files = $request->get('photo');
$urls = [];
foreach ($files as $file) {
$filename = 'files/' . $file['name'];
// Upload File to s3
Storage::disk('digitalocean')->put($filename, $file['blob']);
Storage::disk('digitalocean')->setVisibility($filename, 'public');
$url = Storage::disk('digitalocean')->url($filename);
$urls[] = $url;
}
return response()->json(['urls' => $urls]);
}
// broadcast(new NewChatMessage($newMessage))->toOthers();
// return $newMessage;
}
First: I want to state that if there is something wrong with the current code, just know its because ive been playing around with this for 3 hours now and been trying anything. I am sure at one point I had it close but somehow screwed it up along the way so I am more looking for fresh eyes to show me my error.
That being said, the other part to take into account is in DevTools under Network I can clearly see the blob and can load it up, I can also see the "upload" item and under there the form data which shows the following
------WebKitFormBoundary7qD7xdmiQO9U1Ko0
Content-Disposition: form-data; name="photo"; filename="6A8B48B4-F546-438E-852E-C24340525C20_1_201_a.jpeg"
Content-Type: image/jpeg
------WebKitFormBoundary7qD7xdmiQO9U1Ko0--
it clearly also shows photo: (binary) so I am completely confused as to what I am doing wrong. The ULTIMATE goal here is to get the image, store it as public in S3/DigitalOcean then grab the public URL to the file and store in the DB.
Any help would be GREATLY appreciated!
I would like to pause fineuploader if the document dropped is a pdf to give the end user some options before continuing. I cannot figure out how to get the pause to trigger. I am getting [Fine Uploader 5.3.2] Ignoring pause for file ID 0 (DEVELOPMENT.PDF). Not in progress.
My code below.
var uploader = new qq.s3.FineUploader({
debug: true,
element: document.getElementById('fine-uploader'),
request: {
endpoint: 'bucketname.s3.amazonaws.com',
accessKey: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' //zone-user key id
},
signature: {
endpoint: "/assets/plugins/fine-uploader/signature/endpoint.php"
},
debug:true,
cors: {expected: true},
chunking: {enabled: true},
resume: {enabled: true},
deleteFile:{enabled:false},
validation: {
itemLimit: 5,
sizeLimit: 15000000
},
uploadSuccess:{
//endpoint:"/assets/plugins/fine-uploader/signature/endpoint.php?success"
},
callbacks: {
onSubmitted: function(id, name) {
var fileName = name;
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toUpperCase();
if(fileExtension==='PDF'){
alert('it IS pdf... now what?');
jQuery('#confirmPDFHandler').modal();
uploader.pauseUpload(id); //not pausing here
}else{
alert('its not a pdf... go!');
uploader.continueUpload(id);
}
},
onError: function(id, name, errorReason, xhrOrXdr) {
//alert(qq.format("Error on file number {} - {}. Reason: {}", id, name, errorReason));
},
onUpload: function(id, name, isError,responseJSON) {
var obj = JSON.stringify(responseJSON);
//alert(name + 'is in progress');
},
onComplete: function(id,fileId,responseJSON){
var newfilename=uploader.getKey(id);
}
},
retry: {enableAuto: false}
});
If the user drops a pdf in the uploader, we will give them an option to simply upload (continue as usual) or split the file (pause or stop the upload and run our separate custom code to begin the pdf split option pulling one document into multiple documents then passing those to an uploader)
Sounds like you want to potentially cancel the upload, or proceed. In that case, you should ask the user for input inside of an onSubmit or onValidate event handler. Your handler should return a Promise and either resolve the promise to allow the file to go through, or reject it to cancel the file submission. For example:
onSubmit: function(id) {
return new Promise(function(resolve, reject) {
// popup modal
// when user responds...
// ...call resolve() if they want to upload the file
// ...or reject() if they want to cancel the file
});
}
Fine Uploader has a very small "promise" implementation bundled with the library. It's non-standard, so you may be better off finding a standard A+ implementation instead.
I checked if fineuploader worked on an iPad, and it does mostly, but the iPad only gets a single file "image.jpg" returned, so every file that's uploaded keeps overwriting the previous file. (Or it just uploads one file)
In any case, can this behavior be fixed on either Chrome or Safari on an iPad?
We are using library to uploaded images for different business requirement and its works like dream. thanks for developing this one.
Krishna
here is my code:
I am creating endpoint dynamically and uploading files for different folders. Its getting uploaded for other platform except iOS.
$(document).ready(function () {
$('#s3-fileuploader').fineUploader({
request: {
endpoint: '',
inputName: 'filename',
forceMultipart: true,
paramsInBody: true,
params: {},
},
failedUploadTextDisplay: {
mode: 'custom',
maxChars: 40,
responseProperty: 'error',
enableTooltip: true
},
cors: {
expected: true, //all requests are expected to be cross-domain requests
sendCredentials: false, //if you want cookies to be sent along with the request
allowXdr: true
},
autoUpload: true,
multiple: true,
debug: true,
text: {
uploadButton: '<i class="icon-plus icon-white">Select Files</i> '
},
deleteFile: {
enabled: false,
forceConfirm: true,
},
validation: {
// allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
itemLimit: 75
}
}).on('submit', function (event, id, name) {
$(this).fineUploader('setEndpoint', endPoint); //set endpoint
}).on('complete', function (event, id, fileName, response) {
var $deleteEl = $(
'<span class="delete"> <a href="javascript:;" onclick="deleteFile(\'' +
response.deleteFileUrl + '\',\'' + id +
'\')">Delete</a></span> ');
//when you delete element is clicked, call the "deleteFile" API method, passing in that file's ID
if (response.success) {
$(".qq-uploader").append(
'<div class="highlight" style="margin-top:8px;margin-right:8px;float:left;width:180px;height:194px; box-shadow:1px 0 0 #F3F3F3, 0 1px 0 #E4E4E4, 0 -1px 0 #F3F3F3, -1px 0 0 #F3F3F3" class="thumb" id="thumb_' +
id + '"></div>');
//get file name from responce
var filename = getFileName(response.getThumbnailUrl);
//get file extension now
var fileExt = filename.split('.').pop().toLowerCase();
//create array of all available extenions images
var exts = ["csv", "doc", "docx", "xls", "zip", "pdf",
"txt"
];
//check if its a image
if (fileExt == 'jpeg' || fileExt == 'jpg' || fileExt ==
'png' || fileExt == 'gif' || fileExt == 'tiff' ||
fileExt == 'tif' || fileExt == 'bmp' || fileExt ==
'wbmp') {
//myother logic
}
}
});
});
This is due to the design of iOS, not Fine Uploader. See, iOS names the files for you -- "image.jpg" to be exact.
Fine Uploader mitigates this problem by generating a level 4 UUID and sending that along with the upload request. The parameter to look for in the request body is qquuid.
I'm guessing your server is saving files based on their filename only. A more robust solution would be to use a combination of the file's UUID and filename to ensure users are not overwriting files that already exist.
Your server could prepend the UUID to the filename:
4A0BC570-0125-11E3-B778-0800200C9A66_image.jpg
or create an entirely new folder:
4A0BC570-0125-11E3-B778-0800200C9A66/image.jpg
Not only will this ensure that users uploading on iOS don't overwrite each others' files, but it will also ensure that two users on any platform uploading two different files with the same name won't step on each others' toes.
If you have any server-/client-side code you'd like to share, I can take a peek, modify it and post in here with my answer.