I am new to servlet. What I'm trying to do is upload the file to my server using servlet alongside I send one text value which is file name to change in server side. The problem is I submit the form data to servlet using ajax post but in my servlet, I'm getting null value from request.getParameter.
This is my html;
$("#fileUp").html( "<form enctype='multipart/form-data' id='uploadForm' action='" + url + "/PrjHRService/FileUpload'>"+
"<input name='file' id='file' type='file' size='50'>"+
"<input name='fname' type='text' >"+
"<input id='btnUpload' value='Upload' type='submit'>"+
//"<div id='imgLink'></div>"+
"</form>" );
This is my jquery ajax call to server;
$("#uploadForm").submit(function() {
var formData = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: $("#uploadForm").attr("action"),
data: formData,
async: false,
success: function(data)
{
if(data.res === "true"){
jsi.showMsg("Uploaded Successfully");
$("#imgLink").html("Uploaded Successfully");
}else{
jsi.showMsg("Error Uploading");
}
},
contentType: false,
processData: false
});
return false; // avoid to execute the actual submit of the form.
});
This is how I get the value from form in my servlet; In there you will see the line String fileExt=request.getParameter("fname"); I found out that fileExt is null which is my problem.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("application/json");
String fileExt=request.getParameter("fname");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
JSONObject o=new JSONObject();
try {
o.put("res", "false");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println(o.toString());
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
//String[] parts = fileName.split(".");
//fileName = parts[0] + "." + parts[1];
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
JSONObject o=new JSONObject();
o.put("res", "true");
//out.println("Uploaded Filename: " + fileName + "<br>");
out.println(o.toString());
//out.println("Uploaded Successfully");
}
}
/* out.println("</body>");
out.println("</html>");*/
}catch(Exception ex) {
System.out.println(ex);
}
}
If you want to upload file, <form/>'s method must be set to POST. Then, at the server side, you need to get input stream from the request and read data --- and you need to do that in doPost method (http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29). Of course there are many libraries, that do that from you, e.g. those from apache.
You must remember, that using POST with enctype="multipart/from-data" adds all form's parameters to POST body, what is distinctive from enctype="application/x-www-form-urlencoded" where parameters are concatenated to request URL (as so called QUERY_STRING). Method getParameter works only on parameters sent via URL. So in your case you need to read POST data, parse it and find out the value of fname. POST that might look like this:
-----------------------------8022333619518
Content-Disposition: form-data; name="fname"
myfilename.txt
-----------------------------8022333619518
Content-Disposition: form-data; name="submit"
Send
-----------------------------8022333619518--
If you add manually some parameters to action URL, getParameter method will find it.
And as you do not upload any file (aren't you?) you can set enctype="application/x-www-form-urlencoded" to use getParameter, as it adds all form's inputs to URL. But your code suggests, that you will upload a file later, so it won't work for the file content.
As you use ServletFileUpload from Apache, you can see parseParameterMap method, get the map, then get fname parameter (it should be first element on the list) as FileItem and get its content with getString. It should be what you are looking for:
Map<String, List<FileItem>> map = ServletFileUpload.parseParameterMap(request);
List<FileItem> list = map.get("fname");
if (list != null && list.size() >= 1) {
FileItem item = list.get(0);
System.out.println("And the winner is... " + item.getString);
}
else {
System.out.println("Dammit! Still no luck!");
}
Related
We have a legacy code that enables site user to download a file from the server.
Till now, the downloaded files were CSV and we had no problem.
Now the server also have a zip file - that contains the CSV.
The server generates the zip file correctly (used this tutorial) and in the server we can open the zip file, and extract correctly the inside CSV file.
The problem is when the browser downloads the zip file: The inside CSV file has no CSV suffix and the it can't be open.
The error we get (using 7Zip):
Unexpected end of data
Warnings:
Headers Error
There are some data after the end of the payload data
Backend code for serving the file (Running in Spark-Java microservice):
public Object handle(Request request, Response response) throws Exception {
fileName = ...
response.raw().setContentType("application/zip");
response.raw().setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
try (
FileInputStream fis = new FileInputStream(fileName);
BufferedOutputStream bufferedOutputStream = new BufferedOutptStream(response.raw().getOutputStream());
BufferedInputStream bufferedInputStream = new BufferedInputStream(fis)) {
ByteStreams.copy(bufferedInputStream, bufferedOutputStream);
} catch (Exception e) {
....
}
return response.raw();
}
Front end code (Angular 1) for fetching the file:
$scope.downloadFile = function (fileName) {
$http.get(fileName).
success(function (data, status, headers, config) {
var anchor = angular.element('<a/>');
var headers = headers();
var filename = headers['x-filename'];
var contentType = headers['content-type']
data = new Blob([data], {type: contentType});
var fileUrl = URL.createObjectURL(data);
anchor.attr({
'href': fileUrl,
'target': '_blank',
'download': fileName
})[0].click();
}).error(function (data, status, headers, config) {
$log.info("download " + fileName + " error " + status);
}
);
};
I am trying to implement a file-upload functionality using webkitdirectory with java backend.
Step1. Design a HTML form with webkitdirectory
<form action="DataUpload" method="post" enctype="multipart/form-data">
<input type="text" name="dbName" value="Database Name Here" id="dbName"/>
<input type="file" id="ctrl" webkitdirectory directory multiple/>
<input type="submit" />
</form>
Step 2. Passing information from form to Servlet
public class DataUpload extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response){
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator fileIterator;
try {
fileIterator = upload.getItemIterator(request);
InputStream inputStream = null;
BufferedReader br = null;
System.out.println("CheckPoint 1");
while(fileIterator.hasNext()) {
System.out.println("CheckPoint 2");
FileItemStream item = fileIterator.next();
String inputFileName = FilenameUtils.getName(item.getName());
inputStream = item.openStream();
inputFileName = inputFileName.split("\\.")[0];
List<String[]> list = new ArrayList<String[]>();
// Getting File
br = new BufferedReader(new InputStreamReader(inputStream)); // Getting the object to read file
String line;
while((line = br.readLine())!= null){// While condition ends then end of file is reached.
list.add(line.split(","));
}
// Checking if File is Empty
if (list.size() == 0){
System.err.println("File Empty");
}else{
// TODO : Parameter Parser.
// DO JOB HERE
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My code, doesn't give any programming error, but it does not pass through the CheckPoint 2, i.e. it doesn't go inside the while loop. I tried looking into various post, such as:
Keep Directory Structure When Uploading
How to upload files to server using JSP/Servlet? - While this question shows maximum resemblance to problem in question, This question works for selecting multiple files in a folder, where the problem here is question is to upload files in different sub directories inside a folder.
I was wondering, if this was possible using solely java servlets without using javascript. I was able to upload multiple files inside a single folder. But, code doesn't seem to work, when I select a folder as input, instead it works when I select a particular file or a subset of files.
HTML File Form
<form onsubmit="readFiles()">
<input type="file" name="files" webkitdirectory directory multiple id="files">
<input type="submit">
</form>
JavaScript Function
function readFiles(){
var files = document.getElementById("files").files;
for (var file = 0 ; file < files.length; file++) {
var reader = new FileReader();
reader.onload = function(e){
var object = new Object();
object.content = e.target.content;
var json_upload = "jsonObject=" + JSON.stringify(object);
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "http://localhost:8080/readFileServlet");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);
}
reader.readAsBinaryString(files);
}
}
Java Function:
JSONObject jObj = new JSONObject(request.getParameter("jsonObject"));
in a post method try
make #Autowired ServletContext c;
or take object from it in servlets
byte[] bytes = file.getBytes();
String UPLOAD_FOLDEdR=c.getRealPath("/images");
Path path = Paths.get(UPLOAD_FOLDEdR +"/"+ file.getOriginalFilename());
Files.write(path, bytes);
I am uploading a file using Servlet using the code as follows::
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
out.print("FileName: " + fileName);
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
if (fileName == null || fileName == "") {
resumefilepath = "";
} else {
resumeflag = 1;
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(resumePath + fileName.substring(fileName.lastIndexOf("\\")));
} else {
file = new File(resumePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fi.write(file);
What I am getting is my file is getting uploaded correctly. I needed to upload my file with different name, but make sure that file content should not be changed. Suppose I am having an image 'A.png' then it should be saved as 'B.png'. Please help guys?? I have tried like this:
File f1 = new File("B.png");
// Rename file (or directory)
file.renameTo(f1);
fi.write(file);
But not working
Assuming that you are referring to the Apache Commons FileItem you are simply in control what File instance you pass to FileItem.write. At that point, the File object is just an abstract name and the file will be created by that method.
It is your code which reads the name from the FileItem and constructs a File object with the same name. You don’t have to do it. So when you pass new File("B.png") to the write method of a FileItem representing an upload of A.png the contents will be save in a file B.png.
E.g. to do literally what you asked for you can change the line
fi.write(file);
to
if(file.getName().equals("A.png")) file=new File(file.getParentFile(), "B.png");
fi.write(file);
A simplified version of your code may look like:
String fileName = fi.getName();// name provided by uploader
if (fileName == null || fileName == "") {
resumefilepath = "";
} else {
// convert to simple name, i.e. remove any prepended path
fileName = fileName.substring(fileName.lastIndexOf(File.separatorChar)+1);
// your substitution:
if(fileName.equalsIgnoreCase("A.png")) fileName="B.png";
// construct File object
file = new File(resumePath, fileName);
// and create/write the file
fi.write(file);
}
If you are looking for an answer where you can upload file and change name and insert it into database here it is
<%
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = "/NVS_upload/NVS_school_facilities_img/";
String title=null,description=null,facility_id=null;
ArrayList<String> imagepath=new ArrayList<String>();
String completeimagepath=null;
// Verify the content type
String contentType = request.getContentType();
int verify=0;
//String school_id=null;
String exp_date=null;
String rel_date=null;
int school_id=0;
String title_hindi=null;
String description_hindi=null;
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () ) {
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () ) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
//this genrates unique file name
String id = UUID.randomUUID().toString();
//we are splitting file name here such that we can get file name and extension differently
String[] fileNameSplits = fileName.split("\\.");
// extension is assumed to be the last part
int extensionIndex = fileNameSplits.length - 1;
// add extension to id
String newfilename= id + "." + fileNameSplits[extensionIndex];
//File newName = new File(filePath + "/" +);
//this stores the new file name to arraylist so that it cn be stored in database
imagepath.add(newfilename);
File uploadedFile = new File(filePath , newfilename);
fi.write(uploadedFile);
out.println("Uploaded Filename: " + filePath +
newfilename + "<br>");
}
else if (fi.isFormField()) {
if(fi.getFieldName().equals("title"))
{
title=fi.getString();
out.println(title);
}
if(fi.getFieldName().equals("description"))
{
description=fi.getString();
//out.println(description);
}
if(fi.getFieldName().equals("activity_name"))
{
facility_id=fi.getString();
//out.println(facility_id);
}
if(fi.getFieldName().equals("rel_date"))
{
rel_date=fi.getString();
//out.println(school_id);
}
if(fi.getFieldName().equals("exp_date"))
{
exp_date=fi.getString();
// out.println(school_id);
}
if(fi.getFieldName().equals("school_id"))
{
school_id=Integer.valueOf(fi.getString());
// out.println(school_id);
}
if(fi.getFieldName().equals("title-hindi"))
{
title_hindi=fi.getString();
// out.println(school_id);
}
if(fi.getFieldName().equals("description-hindi"))
{
description_hindi=fi.getString();
out.println(school_id);
}
}
}
out.println("</body>");
out.println("</html>");
} catch(Exception ex) {
out.println(ex);
}
}
else {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
}
%>
<%
try{
completeimagepath=imagepath.get(0)+","+imagepath.get(1)+","+imagepath.get(2);
Connection conn = null;
Class.forName("org.postgresql.Driver").newInstance();
conn = DriverManager.getConnection(
"connection url");
PreparedStatement ps=conn.prepareStatement("INSERT INTO activities_upload (activity_name,title,description,pdfname,publish_date,expiry_date,title_hindi,description_hindi,school_id) VALUES(?,?,?,?,?,?,?,?,?)");
ps.setString(1,facility_id);
ps.setString(2,title);
ps.setString(3,description);
ps.setString(4,completeimagepath);
ps.setDate(5,java.sql.Date.valueOf(rel_date));
ps.setDate(6,java.sql.Date.valueOf(exp_date));
ps.setString(7,title_hindi);
ps.setString(8,description_hindi);
ps.setInt(9,school_id);
verify=ps.executeUpdate();
}
catch(Exception e){
out.println(e);
}
if(verify>0){
HttpSession session = request.getSession(true);
session.setAttribute("updated","true");
response.sendRedirect("activitiesform.jsp");
}
%>
Image upload working on localhost fine using request.getRealPath() but same we are using in server that's not
working, because server can not find specified path.. image can't be displayed .. how i can solved this problem.??
here is code for image uploading:
filePath =request.getRealPath("") + "\\img\\";
System.out.println(filePath);
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0))
{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List fileItems = upload.parseRequest(request);
// message= fileItems.get(2).toString();
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if(fi.isFormField())
{
message=fi.getString();
System.out.println("message is : "+message);
bean.setEmp_id(Integer.parseInt(message));
}
if (!fi.isFormField()) {
String fieldName = fi.getFieldName();
System.out.println("field name"+fieldName);
fileName = fi.getName();
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath
+ fileName.substring(fileName
.lastIndexOf("\\")));
} else {
file = new File(filePath
+ fileName.substring(fileName
.lastIndexOf("\\") + 1));
}
fi.write(file);
The getRealPath() gives the absolute path (on the file system) leading to a file specified in the parameters of the call. It returns the path in the format specific to the OS.
Read request#getRealPathfor its documentation.
Also it is advised to use servletRequest.getSession().getServletContext().getRealPath("/") instead of servletRequest.getRealPath("/") as it is deprecated.
so the best way is to provide the upload path for the server by yourself, as the method values specific to the OS the returned path may not be accessible(Permissions).
Hope this helps !!
Can't figure out why this keeps creating 2 folders? It makes a '0' folder and whatever the jobID is from the html. I want uploaded files in the jobID folder, not the '0' folder.
int userID = 1; // test
String coverLetter = "";
String status = "Review";
int jobID = 0;
String directoryName = "";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart && request.getContentType() != null)
{
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */ items = null;
try
{
items = upload.parseRequest(request);
}
catch(FileUploadException e) {}
// Process the uploaded items
Iterator iter = items.iterator();
while(iter.hasNext())
{
FileItem item = (FileItem)iter.next();
if(item.isFormField())
{
if(item.getFieldName().equals("coverLetter"))
coverLetter = item.getString();
if(item.getFieldName().equals("jobID"))
jobID = Integer.parseInt(item.getString());
}
directoryName = request.getRealPath("/") + "/Uploads/CV/" + jobID + "/";
File theDir = new File(directoryName);
if (!theDir.exists())
theDir.mkdir();
if(item.getFieldName().equals("file"))
{
File uploadedFile = new File(directoryName + item.getName());
try
{
item.write(uploadedFile);
}
catch(Exception e) {}
}
}
Edit:
Problem solved.I want uploaded files
It was because it was in the jobID folder, not the '0' folder.
I suspect this isn't true:
item.getFieldName().equals("jobID")
It's a bit difficult to guess though. Have you tried debugging in Eclipse (or similar)? Adding some logging might help too.
There must be 2 items parsed from the request, So perhaps you are sending 2 upload items.
The first item doesn't have the jobID FieldName so the directory name remain
.../Uploads/CV/0
So thats the time which is causing problems.
The second item does have the job ID so the directory gets created correctly.
Can you post the form so we can see, it may be something on there. Is the cover letter an additional file without jobId?
You could solve it by only creating dir if jobID exists.
Try printing/logging the jobID before the below line:
directoryName = request.getRealPath("/") + "/Uploads/CV/" + jobID + "/";