I use a module that creates customized html forms through template partails
I need to manage 4 file uploads of a form.
In actions I pull all field data like so:
$allData = $request->getParameterHolder()->getAll();
which would get me the uploaded file name, but I need to also save that file to the uploads dir.
I am trying to bind the form like so:
if( isset($customData['getAttachments']) && count($allData)){
$attachments = $formInput->bind($request->getParameter('forms_input'), $request->getFiles('forms_input'));
}
which succesfully generates the $attachments object. Sanity check on that is a var_dump($attachments);die; which dumps:
object(FormsInput)#225 (18) { ["_node":protected]=> NULL ["_id":protected]=> array(1) { ["id"]=> string(5) "32171" } ["_data":protected]=> array(6) { ["id"]=> string(5) "32171" ["form_uid"]=> string(32) "aef79b2d47722ca154788cc9c8f8de2b" ["data_array"]=> string(770) "a:20:{s:9:...
How to I extract the file and push to a directory. I tried this:
$file = $attachments->getValue('file');
if($file) {
$filename = sha1($file->getOriginalName()).$file->getExtension($file->getOriginalExtension());
$file->save(sfConfig::get('sf_upload_dir').'/'.$formTitle.'/'.$usrDir.''.$filename);
}
but it throws this error:
Unknown record property / related component "value" on "FormsInput"
How can I get the uploaded into a sf dir?
UPDATE
Tried to use the sfValidatorFile class, but I cannot figure out how to pass it the parameters from the $attachment object:
$file = new sfValidatorFile();
if($file) {
$filename = sha1($file->getOriginalName()).$file->getExtension($file->getOriginalExtension());
$file->save(sfConfig::get('sf_upload_dir').'/uploadedDir');
}
throws this:
Fatal error: Call to undefined method sfValidatorFile::save()
What you intended to do with the $file->save requires an sfValidatedFile object.
If FormsInput is an instance of sfFormObject, you can configure your form with 4 sfValidatorFile with the path you wanted in option. It will do the job you need.
Related
I have a Blazor Application which had files uploaded to a upload folder on the web server. I am in the process of trying to figure out the code to download an uploaded file in the browser for retrieval and viewing. Right now the code is as below (the download part from code examples on the internet)
public void FileDetailsToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
{
string path = null;
string uploads = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot\\uploads");
path = uploads + "\\" + SelectedFileName;
if (args.Item.Text == "Delete")
{
//Code for Deleting goes here
//UploadRef.Remove();
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
FileDetailsService.FileDetailsDelete(SelectedFileId); //NavigationManager.NavigateTo($"/ServiceRequestNotes/servicerequestnoteadd");
NavigationManager.NavigateTo($"/ServiceRequests/serviceRequestsaddedit2/{Id}", forceLoad: true);
}
else
{
// its a download
IFileProvider provider = new PhysicalFileProvider(uploads);
IFileInfo fileinfo = provider.GetFileInfo(path + SelectedFileName);
var readStream = fileinfo.CreateReadStream();
var mimeType = "application/pdf";
return File(readStream, mimeType, SelectedFileName);
}
}
On the last statement I am a getting the following error message
non-invocable member 'File' cannot be used like a method error message
What am I missing or do I need to change or add to have the output from the readstream render to the browser?
The blazor application is a blazor server app not WASM. It does not make use of API controllers.
Any advice?
This is a void method. You can't return anything at all. Also, if you're trying to instantiate a File object, you'd have to use the new keyword.
How to upload a file in symfony 4.I have done with the symfony document. I don't know where I have missed something. Its throws error while uploading file give me some clues
REFERED LINK:
https://symfony.com/doc/current/controller/upload_file.html
ERROR:
The file "" does not exist
Entity
public function getBrochure()
{
return $this->brochure;
}
public function setBrochure($brochure)
{
$this->brochure = $brochure;
return $this;
}
File upload Listener
class FileUploader
{
private $targetDirectory;
public function __construct($targetDirectory)
{
$this->targetDirectory = $targetDirectory;
}
public function upload(UploadedFile $file)
{
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->getTargetDirectory(), $fileName);
return $fileName;
}
public function getTargetDirectory()
{
return $this->targetDirectory;
}
}
This Symfony tutorial works fine for me so I'll try to explain how and perhaps it will help you or people still looking for an answer, this post getting a bit old.
So first you have to create the FileUploader service in App\Service for better reusability (chapter: Creating an Uploader Service). You can basically copy/paste what they've done here, it works like a charm. Then you need to open your services.yaml in Config folder and explicit your brochure directory:
parameters:
brochures_directory: '%kernel.project_dir%/public/uploads/brochures'
# ...
services:
# ...
App\Service\FileUploader:
arguments:
$targetDirectory: '%brochures_directory%'
Now everything is normally ready to use your FileUploader service.
So if you're in your controller (for example), I guess you want to use it in a form. Thus, you just have to do this (don't forget to use your Service in your Controller):
public function myController(FileUploader $fileUploader)
{
// Create your form and handle it
if ($form isValid() && &form isSubmitted()) {
$file = $myEntity->getBrochure();
$fileName = $this->fileUploader->upload($file);
$myEntity->setBrochure($fileName);
// Form validation and redirection
}
// Render your template
}
One important point I forgot to say. In your FormType, you need to say that the Brochure will be a FileType:
$builder->add('brochure', FileType::class)
But in your entity you have to specify your brochure is stored as a "string":
/**
* #MongoDB\Field(type="string")
*/
protected $brochure;
The reason is your file is getting uploaded and saved in your public/uploads/brochure. But your database is only remembering a string path to reach it.
I hope this will help!
In Elm, how can I access a file on my local drive?
For example, I need to access the file:
c:\MyFolder\somefile.txt
(I'm assuming you're targeting the browser and not Node. If you want Node support, here is the documentation for it's fs module. The high-level usage will be similar to what I'm describing below for browsers.)
There is not (yet) an Elm-only API for this, so you'll have to use ports. This article is very helpful, I will adapt its example.
In short, you have to use File and FileReader API (caniuse.com), and on load of the file send the data to Elm through port. (In my example below, Elm will get a GetFile {name : String, content : String} message for every file submitted.) Here is a working example in Ellie.
Msg:
type Msg
= GetFile File
type alias File =
{ name : String
, content : String
}
Port:
port getFile : (File -> msg) -> Sub msg
(don't forget port module instead of module on top of the Elm source)
Subscription:
subscriptions : Model -> Sub Msg
subscriptions model =
getFile GetFile
HTML file input:
<input type="file" id="files" name="files[]" multiple />
JS (the main part!):
<script>
var app = Elm.Main.fullscreen();
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
app.ports.getFile.send({name: theFile.name, content: e.target.result});
};
})(f);
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
EDIT: this example only accepts images. If you don't want that, remove the
if (!f.type.match('image.*')) {
continue;
}
part and do something different in the viewFile function (ie. don't try to interpret the content data as an image src).
Elm is now able open files as of 0.19.
Steps are as follows:
Attach an event handler to a button that sends the appropriate message to the update function.
Update function receives message and runs the file-opening function, which tells Elm runtime to ask browsers to open a file selection dialogue.
Once user action has completed, Elm runtime returns a data of type File to the update function, and the update function can decide what to do.
To read file's content, a file-reading function has to be invoked. Again, the function tells the Elm runtime to read the content of the file. The runtime again invokes your update function, this time passing the content of the file.
Please refer to this thread on Elm discourse, which includes this example on Ellie app
I currently have this in my grails view to open a pdf file in a new window:
${file.getValue()}<br/><br/>
where file.getValue() is the name of the file with extension.
This defaults to the path of grails-app/assets/userGuides. I want to change this so that it opens the file from a local destination, for example C:/Users/user1/userGuides/
How would I change this ?
If you're in grails 2.x, you can configure a target directory in Config.groovy
For instance
grails.datapath.userguides = "C:/Users/user1/userGuides/"
if you want to configure this depending the environment you can do like this :
development {
grails.datapath.userguides = "C:/Users/user1/userGuides/"
}
test {
grails.datapath.userguides = "C:/anotherDirectory/userGuides/"
}
production {
grails.datapath.userguides = "/var/www/${appName}/userGuides/"
}
Then define a controller to access your files, for example a DocumentsController with this action
def downloadUserGuide()
{
... // code to get your entity file that you use in your example to do
... // file.getValue()
String path = grailsApplication.config.grails.datapath.userguides
String label = ... // If you want to display another file name
render(contentType: "application/pdf", file: new File(path + file.getValue()), fileName: label)
}
public function actionCreate()
{
$model=new Patient('patientScenario');
if(isset($_POST['Patient']))
{
$model->attributes=$_POST['Patient'];
$model->image= CUploadedFile::getInstance($model,'image');
if($model->save())
{
$imagePath = Yii::app()->params['DataFolder'];
if($model->image!="")
{
if(!(file_exists($imagePath)))
{
mkdir($imagePath,'0777',true);
}
}
$model->image->saveAs($imagePath.$model->id.'_'.$model->image->name);
$ns=new newserver(); $ns->uploadFile($filepath,$imagePath.$model->id.'_'.$model->image->name, $model->id.'_'.$model->image->name);
}
}}
It is a action with lot of codes I have simplified it to focus on the issue here.
The issue is while creating a patient, If I upload a image its working fine, But even though I don't upload an image the condition $model->image!="" became true and obviously there will be no file name and while trying to upload on the new server class I get
fopen(22522_): failed to open stream: No such file or directory
I tried ($model->image!==NULL) as well. still getting the same error.
But it works fine in my localhost, But not in the server.
Your problem is on newserver() class
On that class you are tried to open a file .
Check condition before the file open on newserver() class
or give a code on newserver Class