I am not able to upload image with this code, although it is not showing any error but at the same time image is also not saving in folder.
MultipartFile productImage = product.getProductImage();
String rootDirectory = request.getSession().getServletContext().getRealPath("/");
path = Paths.get(rootDirectory + "resources/images/" + product.getProductId() + ".png");
if(productImage != null && !productImage.isEmpty()){
try {
productImage.transferTo(new File(path.toString()));
System.out.println("image edited then saved ");
} catch (Exception ex){
ex.printStackTrace();
throw new RuntimeException("Product image saving failed", ex);
}
}
Related
I am tring to get .csv file from a url, when i loop through the links using the "a" tag, the href that i want doesn't exist. how can i get it's href.
` String URL = internalConstant.getMlcuURL();
String ffiListFile = null;
logger.info("Page URl: " + URL);
Document doc;
try {
doc = Jsoup.connect(URL).get();
Elements links = doc.select("a[href]");
for (Element link : links) {
logger.info("Elements aaaa"+ link);
String absHref = link.attr("abs:href");
if (absHref.endsWith(".csv")) {
logger.info(absHref);
ffiListFile = absHref;
break;
}
}
if (ffiListFile.isEmpty()) {
logger.error("file not found");
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "MLCU File not found in website");
}
this.fileDownloadFFIListService.downloadExcelFile(ffiListFile);
} catch (IOException e) {
e.printStackTrace();
logger.error("download error " + e.getMessage());
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed to download file");
`
Trying to use code in:
http://javasampleapproach.com/spring-framework/spring-data/springdata-mongodb-gridfstemplate-save-retrieve-delete-binary-files-image-text-files
with springboot 1.5.13.
In this code to retrieve an image use GridFSDBFile like this:
GridFSDBFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(imageFileId)));
and later to save in filesystem use this:
imageFile.writeTo
Baeldung has the same code:
http://www.baeldung.com/spring-data-mongodb-gridfs
I have my project in springboot 2.0.2 and this line:
GridFSDBFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(imageFileId)));
throws an error:
Type mismatch: cannot convert from GridFSFile to GridFSDBFile
so, once I have changed to:
GridFSFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(imageFileId)));
no errors, but now I have not available the method:
writeTo
to write to disk.
UPDATE 1:
imageFileId = "5b0bff8b7cc45b32f43b47f4";
GridFSFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(imageFileId)));
try {
File file = new File("c:/JSA/retrieve/" + imageFile.getFilename());
FileOutputStream streamToDownloadTo = new FileOutputStream(file);
//This line doesn't works
gridFSBucket.downloadToStream(imageFile.getId(), streamToDownloadTo);
streamToDownloadTo.close();
} catch (IOException e) {
// handle exception
System.out.println("error: " + e.getMessage());
} catch (Exception e1) {
System.out.println("error1: " + e1.getMessage());
}
UPDATE 2:
try {
File file = new File("c:/JSA/retrieve/" + imageFile.getFilename());
FileOutputStream streamToDownloadTo = new FileOutputStream(file);
System.out.println("imageFile.getId(): " + imageFile.getId());
System.out.println("streamToDownloadTo: " + streamToDownloadTo.toString());
gridFSBucket.downloadToStream(imageFile.getId(), streamToDownloadTo);
streamToDownloadTo.close();
} catch (IOException e) {
// handle exception
System.out.println("error: " + e.getMessage());
} catch (Exception e1) {
System.out.println("error1: " + e1.getMessage());
}
Console
imageFile.getId(): BsonObjectId{value=5b0bff8b7cc45b32f43b47f4}
streamToDownloadTo: java.io.FileOutputStream#3b20c8e2
This line thrown an exception:
gridFSBucket.downloadToStream(imageFile.getId(), streamToDownloadTo);
and return null
Solved
Inject:
#Autowired
MongoGridFsTemplate mongoGridFsTemplate;
GridFSBucket gridFSBucket = GridFSBuckets.create(mongoGridFsTemplate.mongoDbFactory().getDb());
imageFileId = "5b0bff8b7cc45b32f43b47f4";
GridFSFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(new ObjectId(imageFileId))));
try {
File file = new File("c:/JSA/retrieve/" + imageFile.getFilename());
FileOutputStream streamToDownloadTo = new FileOutputStream(file);
gridFSBucket.downloadToStream(imageFile.getId(), streamToDownloadTo);
streamToDownloadTo.close();
} catch (IOException e) {
// handle exception
System.out.println("error: " + e.getMessage());
} catch (Exception e1) {
e1.printStackTrace();
}
I am trying to upload an audio file using the following code on server.Right now, it works perfectly well for image files but not for audios.I think MultipartFile should work with audio files as well.Can any one tell me what is wrong here?
I am getting "The server refused this request because the request entity is in a format not supported by the requested resource for the requested method." error.
Does MultipartFile not work with audio files?If no what is an alternative?
#Transactional
public BaseVO uploadImage(MultipartFile file, long userId){
Map<String, Object> alertParams = new HashMap<String, Object>();
try{
if (!file.isEmpty()) {
Image profileImage = imageRepository.findByUserId(userId);
if(profileImage == null){
profileImage = new Image();
profileImage.setUserId(userId);
}
File dir = null;
String realPath;
if(liveBuild == "true"){
realPath = liveImageUploadRepository;
dir = new File(realPath);
}else{
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
realPath = request.getSession().getServletContext().getRealPath("/") + devImageUploadRepository;
dir = new File(realPath);
}
if (!dir.exists()) {
dir.mkdirs();
}
String finalFileStorePath = realPath + "/" + userId + ".jpg";
File path = new File(finalFileStorePath);
file.transferTo(path);
profileImage.setImagePath(realPath);
//profileImage.setImageName(userId + ".jpg");
profileImage.setImageName(userId+"");
profileImage.setImageType(".jpg");
imageRepository.save(profileImage);
alertParams.put("id", profileImage.getId());
} else {
return new BaseVO(alertParams, Constants.STATUS_OK, Constants.STATUS_OK_MSG);
}
}catch(HibernateException e){
return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG + " " + e.getMessage());
} catch (IllegalStateException e) {
e.printStackTrace();
return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG);
} catch (IOException e) {
e.printStackTrace();
return new BaseVO(alertParams, Constants.STATUS_ERROR, Constants.STATUS_ERROR_MSG);
}
return new BaseVO(alertParams, Constants.STATUS_OK, Constants.STATUS_OK_MSG);
}
I have two classes. MetaDataExtractor(GUI) and MetaData.
MetaData has the method which extracts the metadata from an image. MetaDataExtractor is designed to display the data in a JTextPane. (Please excuse the class names. I know it's a little confusing. I'm fairly new to Java).
MetaDataExtractor:
LongitudeField.setText("" + MetaDataTags.getLongitude());
MetaData:
public String getLongitude() {
try {
Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
if (metadata.containsDirectory(GpsDirectory.class)) {
GpsDirectory gpsDir = (GpsDirectory) metadata.getDirectory(GpsDirectory.class);
GpsDescriptor gpsDesc = new GpsDescriptor(gpsDir);
String Longitude = "" + gpsDesc.getGpsLongitudeDescription();
}
} catch (ImageProcessingException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 1");
} catch (IOException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 2");
}
return longitude;
}
If I set the longitude to be displayed in the JTextPane, it returns "null". If however, I set it to print out on the command line, it prints the longitude fine?
Please excuse me if its a simple solution. I'm still getting to grips with Java.
Java is case sensitive and declare firstly your variable outside of try & catch statement.
Use a IDE like Eclipse to reduce syntax errors like these.
so you should have :
public String getLongitude() {
String longitudeDesc ="";
try {
Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
if (metadata.containsDirectory(GpsDirectory.class)) {
GpsDirectory gpsDir = (GpsDirectory) metadata.getDirectory(GpsDirectory.class);
GpsDescriptor gpsDesc = new GpsDescriptor(gpsDir);
longitudeDesc = "" + gpsDesc.getGpsLongitudeDescription();
}
} catch (ImageProcessingException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 1");
} catch (IOException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 2");
}
return longitudeDesc ;
}
because use zk upload component to upload a image,then insert the context path of the image to the CKEditor is too complex,
and at http://ckeditor.com/demo, you can see that CKEditor can upload image and flash etc,
but in zk, the CKEditor don't have this feature,
is that mean CKEditor in zk can't upload file?
I'm afraid this is not possible with zk.
I wrote a workaround to do this. You have to add a button to your GUI and add this EventListener to the button:
private class onUpload implements EventListener
{
#Override
public void onEvent(Event event) throws Exception
{
Media media = ((UploadEvent) event).getMedia();
if (media.getContentType().contains("image"))
{
reader.upload(media.getStreamData(), media.getName());
String description = edDescription.getValue();
description += "<img alt=\"\" src=\"/" + media.getName() + "\" />";
edDescription.setValue(description);
}
else
{
new Messagebox().show(_T("You can only upload images!"), _T("Not an image!"), Messagebox.OK, Messagebox.ERROR);
}
}
}
Reader is my class which handles file transfers and is used to write the data to the docroot. In my case the docroot of glassfish 3.1 can be located with the following code. I wrote the method getDocFolder() for ist because it also adds subfolders for each user if they don't already exists.
File file = new File("../docroot/");
This is the code for the upload method of the reader:
InputStream inputStream = null;
try
{
inputStream = new ByteArrayInputStream(imageStream);
String filename = getDocFolder()+"/"+imageName;
File file = new File(filename);
OutputStream out=new FileOutputStream(file);
byte buf[]=new byte[1024];
int len;
while((len = inputStream.read(buf)) > 0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (Exception ex)
{
Logger.getLogger(ImageReader.class.getName()).log(Level.SEVERE, "Error writing image", ex);
}
finally
{
try
{
inputStream.close();
}
catch (IOException ex) {}
}
I hope this helps