Hello i am making a servlet that gets the image from a
Everything in my servlet works fine. The only problem is that i want to know what is the name of the uploaded image so that i can store its full path in a database. How to i so that?
This is the code that upload the file but, it doesn't provide me the actual name of the original image. f.getName gives me the name of my tag.
Part f= request.getPart("imgCoverInserisci");
InputStream imageInputStream = f.getInputStream();
System.out.println("Path where image will be saved: "+request.getContextPath()+"/Immagini/");
/*returns null*/ String nomeFile=request.getParameter("imgCoverInserisci");
f.getName(); //return name of input tag
FileOutputStream out = new FileOutputStream ("C:\\Users\\Salvatore\\Documents\\NetBeansProjects\\TestFumettopoli\\web\\Immagini\\copertineFumetti\\"+nomeFile);
// write bytes taken from uploaded file to target file
int ch = imageInputStream.read();
while (ch != -1) {
out.write(ch);
ch = imageInputStream.read();
}
out.close();
imageInputStream.close();
I solved this problem in a different way. I used javascript to parse the name of the file image everytime the Onchange event occured. The javascript function then assigned the name of the file in a hidden input tag. Later the servlet only needed to read this as a parameter and the trick is done!
the javascript code is here
Related
I have a database where the user doesn't has access to.
Still I can go to the database and "read" the documents with for example
var db:NotesDatabase = sessionAsSigner.getDatabase("","somedir/some.nsf");
In this database there's a pdf file I would like to open or download. I have the filename and the unid . If the user had acces to the database I could do it with
http(s)://[yourserver]/[application.nsf] /xsp/.ibmmodres/domino/OpenAttachment/ [application.nsf]/[UNID|/$File/[AttachmentName]?Open
How can I do it with sessionAsSigner without putting a $PublicAccess=1 field on the form ?
edit:
the pdf file is stored as attachment in a richtextfield
second edit
I'm trying to use the XSnippet from Naveen and made some changes
The error message I get is : 'OutStream' not found
The code I tried is :
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename=" + zipFileName);
var embeddedObj:NotesEmbeddedObject = null;
var bufferInStream:java.io.BufferedInputStream = null;
var outStream:java.io.OutputStream = response.getOutputStream();
embeddedObj = downloadDocument.getAttachment(fileName);
if (embeddedObj != null) {
bufferInStream = new java.io.BufferedInputStream(embeddedObj.getInputStream());
var bufferLength = bufferInStream.available();
var data = new byte[bufferLength];
bufferInStream.read(data, 0, bufferLength); // Read the attachment data
ON THE NEXT LINE IS THE PROBLEM
OutStream.write(data); // Write attachment into pdf
bufferInStream.close();
embeddedObj.recycle();
}
downloadDocument.recycle();
outStream.flush();
outStream.close();
facesContext.responseComplete();
Create an XAgent (= XPage without rendering) which takes datebase + documentid + filename as URL parameters and delivers the file as response OutputStream.
The URL would be
http(s)://[yourserver]/download.nsf/download.xsp?db=[application.nsf]&unid=[UNID]&attname=[AttachmentName]
for an XAgent download.xsp in a database download.nsf.
The code behind the XAgent runs as sessionAsSigner and is able to read the file even the user itself has no right to access file's database.
Use Eric's blog (+ Java code) as a starting point. Replace "application/json" with "application/pdf" and stream pdf file instead of json data.
As an alternative you can adapt this XSnippet code from Thomas Adrian. Use download() together with grabFile() to write your pdf-File to OutputStream.
Instead of extracting attachment file to path and reading it from there you can stream the attachment right from document to response's OutputStream. Here is an XSnippet from Naveen Maurya as a good example.
If you can get the PDF file as a stream, you should be able to use the OutputStream of the external context's response.
Stephan Wissel has a blog posting about writing out an ODF file so you should be able to cut that up as a starting point.
http://www.wissel.net/blog/d6plinks/SHWL-8248MT
You already have the db so, you will just need to know the UNID of the document.
var doc = db.getDocumentByUNID(unid) 'unid is a supplied param
var itm:RichTextItem = doc.getFirstItem("Body") 'assuming file is in body field
Once you have the itm, you can loop round all of the embeddedObjects and get the pdf file. At this point, I don't know if you can stream it directly or if you have to detach it, but assuming you detach it, you will then use something like this.
File file = new File("path to file");
FileInputStream fileIn = new FileInputStream(file);
Don't forget to clean up the temporarily detached file
Main thing is that I am fresher in JAVA. I got stuck with some code.
I want to save an image capture by a button directly in a specific folder. up to now I am using a file chooser to save my image
I want to save image in C:\temp and file name can be image,image1,image2 in ascending order
int returnVal = jFileChooser1.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = jFileChooser1.getSelectedFile();
Highgui.imwrite(file.getPath(), frame);
} else {
System.out.println("file access cancelled by user.");
}
I don't know JAVA so someone may give you a more specific answer but all you need to do is add a counter onto your file path. The pseudocode algorithm would be this:
Initialise Counter = 0
Get file path - C:/temp
Get file name - Image
Append counter to file name - Image1
Add on image type - Image1.png
Append file path and name - C:/temp/Image1.png
counter++;
Edit:
Here is a simple System.Out example of how to build up a string:
System.out.println("C:\Temp " + FileName + ".png" );
SUMMARY
I need to store both uploaded and server-generated images, with portable and
predictable paths so my server code is aware of where these images exist.
I need to generate URLs to these images that can be sent to the client. These URLs will be used in HTML image elements.
PROBLEM
My web application allows the user to upload an image, using gwtupload(Apache Commons). This image is stored on the server and a URL returned to the client so the image is shown. gwtupload provides a clientside method to get this URL for the uploaded image. This works in deployment; the following aspects do not:
In certain cases, the uploaded image must be cropped. This results in
a new image being generated by a servlet method. I want to store this
cropped image and return(to the client) an access URL.
Then, this image is used by another method to generate another
image. This method must know the location on the file system of
the previously uploaded(and/or cropped) image. A URL for the new
image must then be returned to client.
I have implementation working perfectly in GWT development mode. However, as I expected, after deployment to my own Tomcat server, the remote services fail due to my confusion regarding the file system. I do not know the correct way of storing these images in a predictable place on the server filesystem, nor do I know how to generate access URLs(for files residing outwith the WAR, as these images will.)
All these images are only needed for the current session, so the locations can be temporary directories. I have spent two days experimenting and trawling the web for a solution to no avail.
I will post abridged code below. This is my attempt to simply use the working directory and relative pathnames. Using the Eclipse debugger attached to my servlet container, I could see the results of String dataDir = context.getRealPath("foo") indicating a temp folder within the servlet: but when I navigated there using explorer, NONE of the files had been written to the disk. I am very confused.
public String[] generatePreview(String xml) {
PreviewManager manager = new PreviewManager();
String url;
try{
preview = manager.generatePreview(xml);
}
catch (Exception e){e.printStackTrace();}
//Create the preview directory
File folder = new File("previews");
if (!folder.exists()) folder.mkdir();
//The file to be written to
File output = new File(folder, "front.jpg");
ServletContext context = getServletContext();
String dataDir = context.getRealPath("previews");
try {
ImageIO.write(image, "jpg", output);
} catch (IOException e) {
e.printStackTrace();
}
url = "previews/" + output.getName();
return url;
}
#Override
public String cropBackground(int[] coord_pair, String relativePath) {
File backgroundsFolder = new File("backgrounds");
if (!backgroundsFolder.exists()) backgroundsFolder.mkdir();
ServletContext context = getServletContext();
String dataDir = context.getRealPath("backgrounds");
File current = new File(relativePath);
String croppedName = "cropped_" + relativePath.replace("./backgrounds/", "");
int x = coord_pair[0];
int y = coord_pair[1];
int width = coord_pair[2];
int height = coord_pair[3];
String croppedPath = null;
try {
croppedPath = imageCropper.createCroppedImage(current, "backgrounds", croppedName, x, y, width, height);
}
catch (IOException e){
e.printStackTrace();
}
current.delete();
return "backgrounds/" + croppedPath;
I am aware that my current 'return' statements would never work in deployment: I need to generate the URLs properly and return as strings. I'm sorry about the question length but I wanted to make my problem clear.
Choose a directory where your images will be stored, outside of Tomcat. Assign some unique ID to each uploaded or generated image, and store the images in this directory (with the ID as file name, for example).
Generate URLs to an image servlet that will read the image by ID in this directory, and send the bytes of the image to the output stream of the servlet response : image.action?id=theImageId.
I am currently working on an application, where users are given an option to browse and upload excel file, I am badly stuck to get the absolute path of the file being browsed. As location could be anything (Windows/Linux).
import org.apache.myfaces.custom.fileupload.UploadedFile;
-----
-----
private UploadedFile inpFile;
-----
getters and setters
public UploadedFile getInpFile() {
return inpFile;
}
#Override
public void setInpFile(final UploadedFile inpFile) {
this.inpFile = inpFile;
}
we are using jsf 2.0 for UI development and Tomahawk library for browse button.
Sample code for browse button
t:inputFileUpload id="file" value="#{sampleInterface.inpFile}"
valueChangeListener="#{sampleInterface.inpFile}" />
Sample code for upload button
<t:commandButton action="#{sampleInterface.readExcelFile}" id="upload" value="upload"></t:commandButton>
Logic here
Browse button -> user will select the file by browsing the location
Upload button -> on Clicking upload button, it will trigger a method readExcelFile in SampleInterface.
SampleInterface Implementation File
public void readExcelFile() throws IOException {
System.out.println("File name: " + inpFile.getName());
String prefix = FilenameUtils.getBaseName(inpFile.getName());
String suffix = FilenameUtils.getExtension(inpFile.getName());
...rest of the code
......
}
File name : abc.xls
prefix : abc
suffix: xls
Please help me in getting the full path ( as in c:.....) of the file being browsed, this absolute path would then be passed to excelapachepoi class where it will get parsed and contents would be displayed/stored in ArrayList.
Why do you need the absolute file path? What can you do with this information? Creating a File? Sorry no, that is absolutely not possible if the webserver runs at a physically different machine than the webbrowser. Think once again about it. Even more, a proper webbrowser doesn't send information about the absolute file path back.
You just need to create the File based on the uploaded file's content which the client has already sent.
String prefix = FilenameUtils.getBaseName(inpFile.getName());
String suffix = FilenameUtils.getExtension(inpFile.getName());
File file = File.createTempFile(prefix + "-", "." + suffix, "/path/to/uploads");
InputStream input = inpFile.getInputStream();
OutputStream output = new FileOutputStream(file);
try {
IOUtils.copy(input, output);
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(input);
}
// Now you can use File.
See also:
How to get the file path from HTML input form in Firefox 3
I remember to have some problem with this in the past too. If I am not mistaken, I think you cannot get the full file path when uploading a file. I think the browser won't tell you it for security purposes.
I have one problem that is to upload file. It is working perfectly on my computer but fails when deploying to a server.
The system is to browse the file, then the system will zip it before uploading it to the server. When a client browse a file, the server will generate an error that the file is not found. Here is my code:
try {
//This is a code to read a zipfile.
String dir = request.getParameter("dirs");
System.out.println(dir);
String tmp = dir.replace( '\\', '/' );
System.out.println(tmp);
String inFilename = tmp;
// String inFilename = dir;
String outFilename = "c:/sms.zip";
//String outFilename = "/webapps/ROOT/sms.zip";
FileInputStream in = new FileInputStream( inFilename);
ZipOutputStream out = new ZipOutputStream(
new FileOutputStream(outFilename));
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(inFilename));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
//End of zipping file.
//Start uploading.
SimpleFTP ftp = new SimpleFTP();
// Connect to an FTP server on port 21.
ftp.connect("xxxxx", 21, "xxx", "xxxx");
// Set binary mode.
ftp.bin();
// Change to a new working directory on the FTP server.
ftp.cwd("web");
// Upload some files.
ftp.stor(new File("sms.zip"));
ftp.disconnect();
//finish uploading
out.closeEntry();
out.close();
in.close();
response.sendRedirect("../BakMeClient/success.jsp");
}
catch (IOException e) {
System.out.println(e);
}
String dir is the location of file.
The error message is:
java.io.FileNotFoundException: D:\RELIVA\listmenu.java (The system cannot find the file specified)
Thanks for all your comments. From my observation the problem is this script is run on the server not on the client.
What I mean is let's say you browse the file for example at c:/test.txt. When you click the upload button, the form will send the path to the server and the server will find the path in its own directory and of course it will not find it.
I hope you get the idea what happened. So now: how to made it read the path at the client?
Here is definitely a problem:
// Upload some files.
ftp.stor(new File("sms.zip"));
The archive has been created at c:/sms.zip but you try to read it from the relative file location sms.zip (which is equal to ${JAVA_HOME}/sms.zip if I remember correctly The correct part is in Joachim's comment, thanks!!).
Replace these lines with
// Upload some files.
ftp.stor(new File("c:/sms.zip"));
If this doesn't help, then in addition try closing the ZipOutputStream before you send the file with FTP. There's a chance that the ZIP file has not been created yet on the file system just because the stream is still open.
There's a major misunderstanding here. You're sending local disk file system paths around instead of the actual file contents. Imagine that I am the client and I have a file at c:/passwords.txt and I give the path to you. How would you as being a server ever get its contents?
With new FileInputStream("c:/passwords.txt")? No, that is fortunately not going to happen. It will only work when both the client and server runs at physically same machine, as you have found out.
Uploading files with HTML (regardless of if it's inside a JSP file) is supposed to be done with an <input type="file"> field as follows:
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
This way the file will be sent in the request body. As the standard Servlet API versions up to with 2.5 doesn't support mulipart/form-data requests, you need to parse the request yourself. The best way is to use Apache Commons FileUpload for this. Follow the link and read both the User Guide and Frequently Asked Questions for code examples and tips&tricks. When you're already on Servlet 3.0, then you can just use the Servlet API provided HttpServletRequest#getParts() for this. You can find here an article with code examples about that.
If you actually want to upload a complete folder with files to the server side and you don't want to use multiple <input type="file"> fields for this, then you'll need Applet or SWF for this, because this isn't possible with plain vanilla HTML. In the server side you can parse the request just the same way.
I think, if it is working in your system and not in server, there must be problem with server settings.
Or you can check following things
Need to check path you are working on.
Before uploading, try to list the files in that directory, once you generate ZIP file.
Check for permissions.
Your outFilename must be found in the web. Like: "http://www.sample.com/sms.zip" or the likes..