I am trying to get an image uploaded by user, store it in a folder(for which I am providing absolute path), store the path in database(Relative path) abd later use the path from database todisplay the image.
I am using cos-MultipartRequest jar file for this.
I don't want to have spaces in the file name(Since the image with spaces in name is not displayed by <img>)
The code I have written is:
String pathUPLOAD="D:/AdvJava/proimp/WebContent/images/default";
String pathDB="images/default";
MultipartRequest m=new MultipartRequest(request,pathUPLOAD);
String file=m.getFilesystemName("file").replaceAll("\\s+",""); //to remove spaces
m.getFile("file").renameTo(new File(pathDB+file)); // to rename the uploaded file without whitespaces
//(tried this earlier) m.getFile("file").renameTo(new File(file));
the path I am inserting in DB is: pathDB+"/"+file
The upload works fine and later the images are also displayed for those which don't have spaces in name.
But for those having spaces, the path stored in DB is the way I want, but the image uploaded in the specified directory does not has any changes in its name and therefore the place where images are to be displayed shows a missing image.
Any suggestions?
Related
So in google-cloud-storage if you upload more than one file with the same name to it the last will overwrite what was uploaded before it.
If I want to upload more than one file with the same name I should append some unique thing to the file name e.g. timestamp, random UUID.
But by doing so I'll lose the original file name while downloading, because I want to serve the file directly from google.
If we used the unique identifier as a folder instead of appending it to the file name, e.g. UUID +"/"+ fileName then we can download the file with its original name.
You could turn on Object Versioning which will keep the old versions of the object around.
Alternatively, you can set the Content Disposition header when uploading the object, which should preserve whatever filename you want on download.
instead of using object versioning, you can attach the UUID (or any other unique identifier) and then update the metadata of the object (specifically the content disposition), the following is a part of a python script i've used to remove the forward slashes - added by google cloud buckets when to represent directories - from multiple objects, it's based on this blog post, please keep in mind the double quotes around the content position "file name"
def update_blob_download_name(bucket_name):
""" update the download name of blobs and remove
the path.
:returns: None
:rtype: None
"""
# Storage client, not added to the code for brevity
client = initialize_google_storage_client()
bucket = client.bucket(bucket_name)
for blob in bucket.list_blobs():
if "/" in blob.name:
remove_path = blob.name[blob.name.rfind("/") + 1:] # rfind gives that last occurence of the char
ext = pathlib.Path(remove_path).suffix
remove_id = remove_path[:remove_path.rfind("_id_")]
new_name = remove_id + ext
blob.content_disposition = f'attachment; filename="{new_name}"'
blob.patch()
I have added custom column to store company logo. I have used file api of moodle like :
$mform->addElement('filepicker', 'certificatelogo', 'Company Logo', null,
array('maxbytes' => $maxbytes, 'accepted_types' => '*'));
$mform->setDefault('certificatelogo', '0');
$mform->addHelpButton('certificatelogo', 'certificatelogo', 'certificate');
Once the form is submitted itemid will be stored in custom column. Say "648557354"
Now I need to get image to print logo on certificate. How can I get image path from itemid? Do I need to store any other information to retrieve image?
The itemid returned is the temporary id of the draft area where the file is stored whilst the form is being displayed. You need to copy the file into its 'real' location, when the form is submitted, otherwise the file will be automatically deleted after a few days (and it will only be accessible to the user who originally uploaded it).
I'd always recommend using the filemanager element, if you are planning on keeping the file around (filepicker elements are for files you want to process and discard, such as when uploading a CSV file data to parse and add to the database).
Details of how to use it are here:
https://docs.moodle.org/dev/Using_the_File_API_in_Moodle_forms#filemanager
But the basic steps are:
Copy any existing files from the 'real' area to the draft area (file_prepare_standard_filemanager).
Display the form.
On submission, copy files from the draft area to the 'real' area (file_postupdate_standard_filemanager).
When you want to display the file to the user, get a list of files stored in the file area (defined by the component, filearea, context and, optionally, itemid, you used in file_prepare_standard_filemanager and file_postupdate_standard_filemanager). You can do this with: $fs = get_file_storage(); $fs->get_area_files().
For those files (maybe only 1 file, in your case), generate the URL with moodle_url::make_pluginfile_url.
Make sure your plugin has a PLUGINNAME_pluginfile() function in lib.php, to examine incoming file requests, do security checks on them, then serve the file.
There is a reasonable example of all of this at: https://github.com/AndyNormore/filemanager
I have form with fields like
'name, firstname, street, zip, city and image'.
The image was an upload
field. Everything works fine, i can upload the image as Filereferrence. But the image was uploaded every time into "fileadmin/". I want to upload the image into "/uploads/<extensionname>" or "fileadmin/user_uploads/<extensionname>".
The part where the upload and file moving was realized look like.
$storageRepository = $this->objectManager->get('TYPO3\\CMS\\Core\\Resource\\StorageRepository');
$storage = $storageRepository->findByUid('1');
$fileData = array();
$fileData['name'] = $_FILES['tx_oaevents_eventslisting']['name']['image'][0];
$fileData['type'] = $_FILES['tx_oaevents_eventslisting']['type']['image'][0];
$fileData['tmp_name'] = $_FILES['tx_oaevents_eventslisting']['tmp_name']['image'][0];
$fileData['size'] = $_FILES['tx_oaevents_eventslisting']['size']['image'][0];
$newFileObject = $storage->addFile(
$fileData['tmp_name'], $storage->getRootLevelFolder(), $fileData['name']
);
This line deines the storage folder form database:
$storage = $storageRepository->findByUid('1');
which is fileadmin as default. But what is the best way to change/modify this storage folder destination?
If you want to specify the destination folder for your upload, I suggest you take a look at the FAL File Upload example from Helmut Hummel. For his example, there is also a blogpost which describes how the file upload works and why you should use a TypeConverter for FAL file upload in TYPO3 6.2+
I have implemented the solution several times and it works just great, since it covers a lot of scenarios you may run into when implementing a file upload (e.g. validation, error handling, file replacement if file exists)
I am working on downloading a image from ftp ,where my ftp contains multiple images with different names generated every time in a folder.I just need to download a image whose name contains thumbs.jpg in it.
For ex i have 4 images with names
2342345232thumbs.jpg
453455345334snap.jpg,
4534532356pic.jpg,
1240897387trim.jpg
from which i want to download a image name which contains thumbs.jpg.
how can i achieve this .please suggest
Assuming you get the contents of the directory or atleast can retrieve the filenames, you could try string matching using NSRange range = [imageName rangeOfString:#"thumbs.jpg"]; if (range.location != NSNotFound) // found match and then download that particular image.HTH.
I have a project with a image stored as a logo that I wish to use.
URL logoPath = new MainApplication().getClass().getClassLoader().getResource("img/logo.jpg");
Using that method I get the URL for the file and convert it to string. I then have to substring that by 5 to get rid of this output "file:/C:/Users/Stephen/git/ILLA/PoC/bin/img/logo.jpg"
However when I export this as a jar and run it I run into trouble. The URL now reads /ILLA.jar!/ and my image is just blank. I have a gut feeling that it's tripping me up so how do I fix this?
Cheers
You are almost there.
Images in a jar are treated as resources. You need to refer to them using the classpath
Just use getClass().getResource: something like:
getClass().getResource("/images/logo.jpg"));
where "images" is a package inside the jar file, with the path as above
see the leading / in the call - this will help accessing the path correctly (using absolute instead of relative). Just make sure the path is correct
Also see:
How to includes all images in jar file using eclipse
See here: Create a file object from a resource path to an image in a jar file
String imgName = "/resources/images/image.jpg";
InputStream in = getClass().getResourceAsStream(imgName);
ImageIcon img = new ImageIcon(ImageIO.read(in));
Note it looks like you need to use a stream for a resource inside an archive.