I am uploading images and videos and creating respective tags for video and audio to display on view page but somehow image and video path are not getting resolved.
Here is my controller.
#RequestMapping(value = "/contentUpload", headers = "content-type=multipart/*", method = RequestMethod.POST)
public #ResponseBody
String uploadImage(#RequestParam("fileData") MultipartFile multipartFile, HttpServletRequest request )
{
String jsonResponse = null;
boolean isImage = false;
boolean isVideo = false;
try
{
String path = request.getServletContext().getRealPath("/");
File directory = null;
if (multipartFile.getContentType().contains("image"))
{
directory = new File(path + "/uploads/images/");
isImage = true;
}
else
{
directory = new File(path + "/uploads/videos/");
isVideo = true;
}
byte[] bytes = null;
File file = null;
bytes = multipartFile.getBytes();
if (!directory.exists()) directory.mkdirs();
file = new File(directory.getAbsolutePath() + System.getProperty("file.separator") + multipartFile.getOriginalFilename());
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
stream.write(bytes);
stream.close();
if (isImage)
jsonResponse = "<br /><img src=\"" + file.getAbsolutePath() + "\" />";
else if (isVideo)
jsonResponse = "<video>" + "<source src=\"" + file.getAbsolutePath() + "\" type=\"" + multipartFile.getContentType() + "\">" + "</video>";
}
catch (Exception e)
{
}
return jsonResponse;
}
I have tried resources settings in dispatcher.
<mvc:resources mapping="/uploads/**" location="/#{servletContext.contextPath}/uploads/" />
uploaded image path.
/home/govi/demo/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/projectImg/uploads/images/batman.jpg
please suggest me the changes required.
Use below code line, it may helps you.
<mvc:resources mapping="/uploads/**" location="/WEB-INF/projectImg/uploads/" />
'///' triple slash solved my issue. Now my resource mapping is like this.
<mvc:resources mapping="/uploads/**" location="file:///home/govi/uploads/" />
Anyone facing this issue please go through JB Nizet's comments and also go through this link How to retrieve and display images from a database in a JSP page?
Related
Hey I'm trying to delete a image (file) but I can't :(
That how I upload the image:
try {
List<String> imagesPaths = new ArrayList<>();
for (String image : imagesBytes)
{
String base64Image = image.split(",")[1];
byte[] imageByte = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
String folder = "C:/images/" + LoggedInUser.UserId();
File newDirectory = new File(folder);
if (!newDirectory.exists())
{
newDirectory.mkdirs();
}
long timeMilli = new Date().getTime();
String imageType = image.substring("data:image/".length(), image.indexOf(";base64"));
String path = timeMilli + "." + imageType;
Files.write(Paths.get(folder, path), imageByte);
String newPath = LoggedInUser.UserId() + "/" + path;
imagesPaths.add(newPath);
}
logger.debug("uploadImages() in ImageService Ended by " + LoggedInUser.UserName());
return new ResponseEntity<>(imagesPaths, HttpStatus.OK);
} catch (Exception e) {
throw new ApiRequestException(e.getMessage());
}
And this how I delete it :
List<ImageJpa> images = imageRepository.findByStatus(Image.UNUSED.status);
System.out.println(images.size() + ": Images are not used");
images.forEach(image -> {
String imagePath = "C:/images/" + image.getPath();
System.out.println(imagePath);
File imagePathFile = new File(imagePath);
if (imagePathFile.exists())
{
boolean isDeleted = imagePathFile.delete();
if (isDeleted)
{
imageRepository.deleteById(image.getId());
System.out.println("Deleted the file: " + imagePathFile.getName());
} else {System.out.println("Failed to delete the file. :" + imagePathFile.getName());}
}else {
System.out.println("Already Deleted");
}
});
Always I got (Failed to delete the file ...)
Note : The image will deleted if I ReRender the the project again or close and open the IDE.
The problem was on other function :\
I was open the files after save it without CLOSE the connection after it !
This one what was messing on the read files
inputStream.close();
I have Web Application hosted on Linux, contains page to upload .rar file and another page to download it. for upload function working fine and file uploaded successfully to server but for download it gives me below exception:
[servelt.scriptdownloadservelt] in context with path [/OSS-CPE-Tracker] threw exception
java.io.FileNotFoundException: \usr\local\apache-tomcat-8.5.31\OSS-CPE-Tracker\Zaky\QCAM.rar (No such file or directory)
I used below funcation to make upload:
String destDir = "/usr/local/apache-tomcat-8.5.31/OSS-CPE-Tracker/Zaky";
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
if(name.equalsIgnoreCase("QCAM.rar")) {
File destFile = new File(destDir, "QCAM.rar");
if (destFile.exists()) {
destFile.delete();
}
item.write(new File("/usr/local/apache-tomcat-8.5.31/OSS-CPE-Tracker/Zaky" + File.separator + name));
request.setAttribute("gurumessage", "File Uploaded Successfully");
}else {
request.setAttribute("gurumessage", "Kindly use the agreed name");
}
and here function for download that i face issue on it and above exception appear:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String gurufile = "QCAM.rar\\";
String gurupath = "\\usr\\local\\apache-tomcat-8.5.31\\OSS-CPE-Tracker\\Zaky";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ gurufile + "\"");
FileInputStream fileInputStream = new FileInputStream(gurupath
+ gurufile);
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close();
The only reason for this error is that file cannot be found under that path.
Please verify the path
String gurufile = "QCAM.rar\\";
String gurupath = "\\usr\\local\\apache-tomcat-8.5.31\\OSS-CPE-Tracker\\Zaky";
// <...>
FileInputStream fileInputStream = new FileInputStream(gurupath
+ gurufile);
In unix systems file path is resolved using forward slash / and not a backslash \.
Try changing to the same value as your upload script:
FileInputStream fileInputStream = new FileInputStream("/usr/local/apache-tomcat-8.5.31/OSS-CPE-Tracker/Zaky/QCAM.rar")
That should do
I am working on java project. In this I have done the code to convert ods file to html and then open that converted file in browser.
Below is my code :-
private String ConvertOdtAndOdsToHTML(String sDocPath, String finalDestinationPath, String downloadImagePath, String returnPath) {
try {
String root = finalDestinationPath;
int lastIndex = sDocPath.lastIndexOf(File.separator);
String sFileName = sDocPath.substring(lastIndex + 1, sDocPath.length());
String fileNameWithOutExt = FilenameUtils.removeExtension(sFileName);
String fileOutName = root + File.separator + fileNameWithOutExt + ".html";
InputStream in = new FileInputStream(new File(sDocPath));
String ext = FilenameUtils.getExtension(sDocPath);
OdfTextDocument document = null;
OdfSpreadsheetDocument odfSpreadsheetDocument = null;
if (ext.equalsIgnoreCase("odt")) {
document = OdfTextDocument.loadDocument(in);
}
else if (ext.equalsIgnoreCase("ods")) {
odfSpreadsheetDocument = OdfSpreadsheetDocument.loadDocument(in);
}
org.odftoolkit.odfdom.converter.xhtml.XHTMLOptions options = org.odftoolkit.odfdom.converter.xhtml.XHTMLOptions.create();
// Extract image
String sLocalSystemImagePath = finalDestinationPath + File.separator+"images"+File.separator;
File imageFolder = new File(sLocalSystemImagePath);
options.setExtractor( new org.openskye.resource.FileImageExtractor( imageFolder ) );
// URI resolver
String localHostImagePath = downloadImagePath + File.separator+"images"+File.separator;
FileResolverOdt fileURIResolver = new FileResolverOdt(new File(localHostImagePath));
options.URIResolver(fileURIResolver);
// URI resolver
OutputStream out = new FileOutputStream(new File(fileOutName));
if (ext.equalsIgnoreCase("odt")) {
org.odftoolkit.odfdom.converter.xhtml.XHTMLConverter.getInstance().convert(document, out, options);
}
else if (ext.equalsIgnoreCase("ods")) {
org.odftoolkit.odfdom.converter.xhtml.XHTMLConverter.getInstance().convert(odfSpreadsheetDocument, out, options);
}
return returnPath + File.separator + fileNameWithOutExt + ".html";
} catch (Exception e) {
return "Failed to open the document: " + sDocPath + " due to error:" + e.getMessage();
}
}
I am able to convert ods file to html and file is getting open in browser also but it is displaying some question marks ???? and date and time in browser.
I just want to display the file as it gets open in open office without displaying date time and any special character. Also I want to differentiate the sheets.
Here is ods file which I want to convert Link
Below is attached screenshot for the ods file that is converted to html
I would be thankful if anyone could help me in finding the solution.
Hi to you all java experts.
I have this piece of code I could finally put together that works: (it's mostly java with a little ADF code)
public String upload(){
UploadedFile myfile = this.getFile();
FacesContext fctx = FacesContext.getCurrentInstance();
ServletContext servletCtx =
(ServletContext)fctx.getExternalContext().getContext();
String imageDirPath = servletCtx.getRealPath("/");
String nomdefichier = myfile.getFilename();
String mimetype = nomdefichier.substring(nomdefichier.length() - 3);
try {
InputStream inputStream = myfile.getInputStream();
BufferedImage input = ImageIO.read(inputStream);
File outputFile =
new File( System.getProperty("user.home") + File.separator + this.path + File.separator + nomdefichier);
ImageIO.write(input, mimetype, outputFile);
} catch (Exception ex) {
// handle exception
}
FacesMessage message =
new FacesMessage(mimetype + "Successfully uploaded file " + nomdefichier +
" (" + myfile.getLength() + " bytes)" + mimetype);
fctx.addMessage(null, message);
return null;
}
This codes uploads a picture just fine. I would really like to know if there is a file equivalent to ImageIO.write so that I could upload PDF, DOCX and such.
Thanks in advance for any response.
Best regards.
Marc Arbour
A simplified version of your code could be written as follows (omitting some of the JSF related stuff).
InputStream in = myFile.getInputStream();
Files.copy(in, Paths.get(yourPath));
You can write a byte array or an InputStream to a file with the java.nio.file.Files class (since Java 1.7).
// Saving data from an inputstream to a file:
Files.copy(inputStream, targetPath, copyOptions...);
// Saving a byte array to a file:
Files.write(path, byteArray, openOptions...);
I am hosting a website on Tomcat server. The application uses Struts 1.1 and Spring for all its operations. I have a page that is used for uploading files to the server.
When user uploads any file it is successfully uploaded but gives a 404 error when tried to retrieve. I checked the file using SSH login, the uploaded file is present in that location. I am scratching my head over this problem from past 4 days but no solution. Its works properly without any problems in my local machine. The problem in there in the deployment.
An Important note: From SSH login, If i try to move that file to some other location and then place it back to its original location, i am able to retrieve the file..!!! I don't know why but I can't do this for every file uploaded by the user. So i modified the my code so that the file is uploaded to a temp location first and then moving it to the correct location. But even this is not working.
FileOutputStream outputStream = null;
FormFile formFile = null;
String tempFilePath = getServlet().getServletContext()
.getRealPath("/")
+ "uploads"
+ System.getProperty("file.separator") + "temp";
try
{
formFile = uploadForm.getFile();
boolean errorflag = false;
if(formFile.getFileSize() > 10660000)
{
request.setAttribute("error",
"File size cannot exceed 10MB!");
errorflag = true;
}
else
{
errorflag = validateFileUpload(request,
formFile, errorflag);
}
if(errorflag)
{
return gotoKnowledgeSharingPage(mapping,
request, actionHelper, session, userid,
instid);
}
File folder = new File(tempFilePath);
if(!folder.exists())
{
folder.mkdir();
}
outputStream = new FileOutputStream(new File(
tempFilePath, formFile.getFileName()));
outputStream.write(formFile.getFileData());
}
finally
{
if(outputStream != null)
{
outputStream.flush();
outputStream.close();
}
}
String finalFilePath = getServlet().getServletContext()
.getRealPath("/")
+ "uploads"
+ System.getProperty("file.separator")
+ session.getAttribute("userid");
//+ System.getProperty("file.separator")
// + formFile.getFileName();
File oldPath = new File(tempFilePath
+ System.getProperty("file.separator")
+ formFile.getFileName());
// Move file to new directory
File newPath = new File(finalFilePath);
if(!newPath.exists())
{
newPath.mkdir();
}
boolean success = oldPath.renameTo(new File(
finalFilePath, formFile.getFileName()));
if(success)
{
actionHelper.insertIntoUploadTable(userid,
knowledgeForm, formFile.getFileName());
}
else
{
if(oldPath.exists())
{
oldPath.delete();
}
}