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.)
Related
We have a legacy system and user wants to change the file upload page.I looked into pulpload and implemented the UI changes. Now for our java changes we are using an in house framework with web macro and it works like this
<form method="post" name="transmitter" action="$url" enctype="multipart/form-data">
..<INPUT TYPE="FILE" name="path_and_filename" id="path_and_filename" size="50">...
</form>
Java Code:
MultipartDocument uploadedFile = (MultipartDocument) data.get("path_and_filename");
Here this MultipartDocument is part of jar which give us all the info we needed for file uploaded like mimetype, docData, docName etc.
Issue: Pulpload doesn't uses input type= file so how are we suppose to do this, as we can't change the Java code [aslots of other pages are using the same framework].
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>
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.
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.