Just like title, I want to ask, how to adding pdf files with upload form to my storage folder (e.g: uploadData) then its added to database as a file too in JSP.
If it not possible, it's ok to added to database as a text.
If it possible as a file, what type of my table for that pdf? blob? or text?
I accept blog links/other links that relevant for my problem
sorry for bad english.
Servlet 3.0 container's has standard support for multipart data. It also has the support to write to local file system. First you should be writing a HTML page which takes the file input along with other input parameters.
<form action="uploadservlet" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<input type="text" name="age" />
<input type="file" name="photo" />
<input type="submit" />
</form>
Now write a UploadServlet which uses the Servlet 3.0 Upload API. Here is the code which demonstrates the usage of API. Fist the servlet handling multipart data should define MultiPartConfig using any of the two approaches:
#MultiPartConfig annotation on Servlet Class
In web.xml, by adding entry inside definition.
Here is the UploadServlet,
#MultipartConfig
public class UploadServlet extends HttpServlet
{
protected void service(HttpServletRequest request,
HttpServletResponse responst) throws ServletException, IOException
{
Collection<Part> parts = request.getParts();
if (parts.size() != 3) {
//can write error page saying all details are not entered
}
Part filePart = httpServletRequest.getPart("photo");
InputStream imageInputStream = filePart.getInputStream();
//read imageInputStream
filePart.write("somefiepath");
//can also write the photo to local storage
//Read Name, String Type
Part namePart = request.getPart("name");
if(namePart.getSize() > 20){
//write name cannot exceed 20 chars
}
//use nameInputStream if required
InputStream nameInputStream = namePart.getInputStream();
//name , String type can also obtained using Request parameter
String nameParameter = request.getParameter("name");
//Similialrly can read age properties
Part agePart = request.getPart("age");
int ageParameter = Integer.parseInt(request.getParameter("age"));
}
}
If you are not using Sevlet 3.0 Container, you should be truing Apache Commons File Upload. Here are the links for using Apache Commons File Upload:
Using Apache Commons File Upload
Apache Commons File Upload Example
References:
File Upload Using Servlet 3.0
Servlet 3.0 javax.servlet.http.HttpServletRequest API
Servlet 3.0 javax.servlet.http.Part API
Uploading File using Servlet 3.0
The easiest way I know of to handle file uploads is by using Commons FileUpload. The documentation gives you a step by step overview of how to accept uploaded files, including how to easily copy them into a file.
Should you decide to put the PDF in a database (I wouldn't do that), BLOB is your best choice, a PDF file isn't text.
I would however advise not to cram all that logic in a JSP but in a servlet instead.
Related
i am using play framework 2.1.2 using java and i am creating view to upload multiple files and my code is here :
#form(action = routes.upload.up, 'enctype -> "multipart/form-data") {
<input type="file" name="picture" accept="application/pdf" multiple="multiple"><br/>
<input type="submit" value="upload">
}
i want to upload only doc and pdf file.
how to restrict form to upload only doc and pdf file ?
i can this with java but i am looking for html code.
after this i want to store multiple file to permanent storage in my computer.
and print name of file i uploaded.
my code :
public static Result up(){
MultipartFormData md=request().body().asMultipartFormData();
List<FilePart>file;
file=md.getFiles();
for(FilePart p: file){
Logger.info(p.getFilename());
}
return ok(file.get(0).getFilename());
}
it is storing file into temp directory but i want to store to permanent location not on temp directory as a file not temp file like if i upload a.docx i want to store this file into storage with a.docx name.
i don't want to store file into database.
and how to list all file that i uploaded by file name?
i found some question but i am not getting that answers because that question is for old version.
give me some idea to fix this issue.
Here is how I implemented mine. I apologize if I made any mistakes somewhere. I "refactored" it so that it doesn't look anything like my production code.
In HTML I have:
<form name="fileUploadForm" method="POST" enctype="multipart/form-data" action="#routes.Application.upload()">
File 1: <br /> <input type="file" name="filePart1" id="filePart1"><br />
File 2: <br /> <input type="file" name="filePart2" id="filePart1"><br />
</form>
In my controller I have:
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart filePart1 = body.getFile("filePart1");
FilePart filePart2 = body.getFile("filePart2");
File newFile1 = new File("path in computer");
File newFile2 = new File("path in computer");
File file1 = filePart1.getFile();
File file2 = filePart2.getFile();
InputStream isFile1 = new FileInputStream(file1);
InputStream isFile2 = new FileInputStream(file2);
byte[] byteFile1 = IOUtils.toByteArray(isFile1);
byte[] byteFile2 = IOUtils.toByteArray(isFile2);
FileUtils.writeByteArrayToFile(newFile1, byteFile1);
FileUtils.writeByteArrayToFile(newFile2, byteFile2);
isFile1.close();
isFile2.close();
}
Just like Kris said, you will have to get Apache's CommonIO
You can easily do this buy adding this into your Build.scala found in /PlayProject/project:
import sbt._
import Keys._
import play.Project._
import com.typesafe.config._
object ApplicationBuild extends Build {
val appDependencies = Seq(
"commons-io" % "commons-io" % "2.4" //add this here
)
}
In this implementation, you can store the files anywhere on your computer where you specified in File newFile1. But you will have to use a database if you want to list your files. But you only have to store the file path as a String (varchar) in the database. I will leave that part up to you to figure out as I don't know how you want to handle file retrieval.
You can restrict user to only upload certain type of files by using Javascript. Have Javascript do form validation by checking the file name: Here is an example:
<script>
var file1 = document.getElementById("filePart1").value;
if (file1.indexOf(".pdf") == -1) {
alert("Not a PDF file!");
else {
document.fileUploadForm.submit();
}
</script>
Hope all of that helps.
To get your file somewhere else than temp location you would need to copy it, best using something like FileUtils from apache commons (http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html)
As for the file names you can get it from MultipartFormData
First getFiles() method
Second getFile():File method
One way could be is to use a custom body parser that can take a specified directory and save the uploaded files there. But you have to add some Scala code to the project. Here is the gist:
https://gist.github.com/nraychaudhuri/6349808
Background: I have to support multiple file uploads in IE7-9. I've found uploadify and FileReader which are both flash based.
Our current file upload allows the user to select a file, type in a description and check some check boxes. That data is all sent to the upload servlet at the same time and the servlet gets the file data and the description and the checkbox values and stores the file on the server and adds an entry into the database.
The problem: uploadify and FileReader both want to send the file directly to the server, I don't have a chance to add a description or set any flags. I've worked with FileReader some now and can intercept the file instead of sending it to the server. What I would like to do is get the binary data and put it into the form, let the user add the description and then submit the form with the binary file data.
I've all ready tried just adding a hidden field to the form but the data didn't seem to come through.
If worse comes to worse I think I could just upload the file and then update the database when the form is submitted, I don't want to do that but I think that would work.
Does anyone know of anyway to add the file data to the form and then to get the servlet to recognize that data as part of the form?
You can pass data along side your upload in Uploadify, just use the formData attribute like this (found here):
<input name='someKey' type='text' value='Some Value'/>
<input type="file" name="file_upload" id="file_upload" />
<script>
$('#file_upload').uploadify({
// Some options
'method' : 'post',
'formData' : { 'someKey' : $('input[name=someKey]').val() }
});
</script>
I'm currently writing a program using nanoHTTPD to upload files to a server. Currently I can successfully upload the file with a preassigned name. However, I would like to maintain the original name of the file being uploaded.
How it uploads now:
Original filename: foo.jpg
Uploaded filename: file123.whatever
How I want it to upload:
Original file name: foo.jpg
Uploaded filename: foo.jpg
Here is the HTML being used:
<FORM ENCTYPE="multipart/form-data" ACTION="/uploaded.html" METHOD=POST>
Upload a file: <INPUT NAME="userfile1" TYPE="file">
<INPUT TYPE="submit" VALUE="Send File">
</FORM>
Here is the vanilla nanoHTTPD code for reference: http://pastebin.com/pMNS3VKf
Note: I would prefer to use Java SE and avoid Java EE.
Any advice would be welcomed, thank you.
Edit: in short all I need to learn how to do is get the filename from the HTML POST.
I'm not certain if your NanoHTTPD is the same as mine, but with mine you can retrieve the original filename by looking at the parms Parameters object for the same key that you retrieve the file from the files Parameters object.
Enumeration<Object> keys = files.keys()
while (keys.hasMoreElements())
{
String key = keys.nextElement().toString();
String origFileName = parms.getProperty(key);
String fsFileName = files.getProperty(key);
this.renameFile(fsFileName, origFileName);
}
Once you retrieve the filename, you can use whatever method you want to rename the file. (With proper checking. It could be a huge security hole if you completely trusted their original filename.)
i written some code in JSP like this--
<input type="file" name="imagename" >
and in servlet i am retrieving 'imagename' value. But it is giving the name of the image instead of full path. My servlet code is like this:
String imagename = request.getParameter("imagename");
and i dont want to use javascript. any ideas? Thanks in advance
Maybe you should checkout this question: How to get the file path from HTML input form in Firefox 3
There is little to no reason why server should have to know full file path. If you want to upload a file, you'll need to use an appropriate library like Apache Commons FileUpload and transfer the file using.
<form action="upload-script-url" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
Apache Commons FileUpload will then accept and transform encoded file into a usable form.
Otherwise you'll need to use JavaScript to get that path.
Assuming that you are trying to upload a file to your server, please note that file uploads are a little more than what you are trying to do - do not expect that if you have a "file" input type in a form, on submission the file just reaches your sever, with no effort. There is a certain procedure to do that.
This article might e a good reference : http://www.cs.tut.fi/~jkorpela/forms/file.html
For Java, use Apache's commons-fileupload : http://commons.apache.org/fileupload/
imagename contains the variable you pass to the servlet... the actual HTTP request parameter. If you want the full path, be sure that the program that is calling your HTTP page is passing the full path instead of just the image name.
This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 7 years ago.
How can I upload files and get other paramaters of a form? I want to handle multi part requests in Java servlet.
To browse and select a file for upload you need a <input type="file"> field in the form. As stated in the HTML specification you need to use the POST method and the enctype attribute of the form has to be set to multipart/form-data.
<form action="uploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>
After submitting such a form the form data is available in multipart format in the HttpServletRequest#getInputStream(). For testing(!) purposes you can read the stream using the following snippet:
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
You however need to parse the stream byte by byte (instead of char by char). Prior to the fresh new Servlet 3.0 API, the standard Servlet API didn't provide any builtin facilities to parse them. The normal form fields are also not available the usual request.getParameter() way, they are included in the multipart form data stream.
If you're not on Servlet 3.0 yet (which is only bit less than 2 monts old), then you need to parse the stream yourself. Parsing such a stream requires precise background knowledge of how multipart form data requests are specified and structured. To create a perfect multipart parser you'll have to write a lot of code. But fortunately there's the Apache Commons FileUpload which has proven its robustness with years. Carefully read both the User Guide and Frequently Asked Questions to find code examples and learn how to use it to an optimum degree (take MSIE into account!).
Step 1
Read adatapost's post.
Step 2
Check out the Apache Commons FileUpload project.
There's a similarly workable solution by O'Reily, but its license of use requires you buy a book, and even that requirement is so poorly articulated that I won't benefit it with yet another link.
Step-1
set enctype form tag attribute.
<form enctype="multipart/form-data" ....>
<input type="file" id="file1" name="file"/>
.... other stuff
</form>
Step-2
Read Justin's post.
To deal with enctype="multipart/form-data" we can not use request.getParameter() directly
Now to deal with the problem
Now, for uploading a file to the server, there can be various ways. But, I am going to use MultipartRequest class provided by oreilly. For using this class you must have cos.jar file.
public class UploadServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
MultipartRequest m=new MultipartRequest(request,"d:/new");
out.print("successfully uploaded");
}
}
this will upload your file to d:/new
Now to retrive parameter of multipart request
you have to use FilenameUtils class and getOriginalFileName() method of MultipartRequest class.
String file = FilenameUtils.getName(req.getOriginalFileName("myfile"))+"\\";
String message = req.getParameter("message");
This does not work for IE7 and below. Apparently you need to add another attribute to your form encoding ="multipart/form-data"