I have the following code that does fileupload. It works but I need to make the upload asynchronous with user not waiting for the upload to finish.
#Path("/files")
public class JerseyFileUpload {
private static final String SERVER_UPLOAD_LOCATION_FOLDER = "C://uploadedtest/";
/**
* Upload a File
*/
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(FormDataMultiPart form) {
FormDataBodyPart filePart = form.getField("file");
ContentDisposition headerOfFilePart = filePart.getContentDisposition();
System.out.println("============================================");
System.out.println("Header is: " + headerOfFilePart.getFileName());
System.out.println("============================================");
InputStream fileInputStream = filePart.getValueAs(InputStream.class);
String filePath = SERVER_UPLOAD_LOCATION_FOLDER+headerOfFilePart.getFileName();
// save the file to the server
saveFile(fileInputStream, filePath);
String output = "File saved to server location using: " + filePath;
return Response.status(200).entity(output).build();
}
// save uploaded file to a defined location on the server
private void saveFile(InputStream uploadedInputStream, String serverLocation) {
try {
OutputStream outpuStream = new FileOutputStream(new File(
serverLocation));
int read = 0;
byte[] bytes = new byte[1024];
outpuStream = new FileOutputStream(new File(serverLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);
}
outpuStream.flush();
outpuStream.close();
uploadedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My Html file is like this
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form Page</title>
</head>
<body>
<h1>Select a file to upload</h1>
<form action="rest/files/upload" method="post" enctype="multipart/form-data">
<p>
Select a file : <input type="file" name="file" size="45" />
</p>
<input type="submit" value="Upload It" />
</form>
</body>
</html>
My requirement is to make it asynchronous and run it as OCTECTSTREAM instead of Multipart as my files are going to be bigger mostly like 5gb plus. Thank you for the help.
Related
I have a source I think should work but for some reason it gives me resource not found and a completely different resource.
HTML part, just simple form:
<html lang="en">
<head>
<title>File Uploader</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="POST" action="upload" enctype="multipart/form-data" >
File:
<input type="file" name="file" id="file" />
<input type="submit" value="Upload" name="upload" id="upload" />
</form>
</body>
</html>
Java part:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
#WebServlet(name = "FileUploader", urlPatterns = "upload")
#MultipartConfig
public class FileUploader extends HttpServlet {
private final static String serverPath = "/fileuploads";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=UTF-8");
final Part filePart = request.getPart("file");
String fileName = getFileName(filePart);
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(serverPath + File.separator + fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + serverPath);
} catch (FileNotFoundException fne) {
writer.println("Missing file or no insufficient permissions.");
writer.println(" ERROR: " + fne.getMessage());
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
private String getFileName(Part filePart) {
String header = filePart.getHeader("content-disposition");
String name = header.substring(header.indexOf("filename=\"")+10);
return name.substring(0, name.indexOf("\""));
}
}
I would expect the file to be uploaded to /proj/publ/fileuploads but insted it tells me that the resource /proj/publ/uploads is not available....
The files are in /proj/publ/ folder. Why is it always pointing to that folder that does not exist?
Thank you for your help.
Viking
EDIT: Prob is solved... for some reason I created the java file in src and not in WEB-INF/src... so there was the problem.
The resource is not available because the servlet is not mapped to any URL pattern. This can be done either by XML declaration in /WebContent/WEB-INF/web.xml or by #WebServlet annotation.
I see that you already use #WebServlet so you have to add urlPatterns element. Something like this:
#WebServlet(urlPatterns = "upload", name="FileUploader")
Another thing to solve is the form's action attribute. Based on the servlet container and its configuration the resource won't be available at the root of the container. It usually is in the form of host:port/application-context/url-pattern however this is not a strict rule. To avoid constant changes what is the right URL you can use JSTL's url tag. Something like this:
form method="POST" action="<c:url ='/upload' />" enctype="multipart/form-data" >
basically resource not found is when the file we are trying to request is not found or the path of resource is not there.
In your case please declare urlPattern in the webServlet annotation like this.
#WebServlet(urlPatterns="/upload")
#WebServlet[https://docs.oracle.com/javaee/6/api/javax/servlet/annotation/WebServlet.html]
When I am using Jquery with spring MVC I got an error at browser side "Bad Request" and control not going to the controller.While I am using simple form and sending a request to same controller then it is going.
Below is my code please tell me where am I going wrong?
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="files/jquery-1.10.2.js"></script>
<script src="files/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var isJpg = function(name) {
return name.match(/jpg$/i)
};
var isPng = function(name) {
return name.match(/png$/i)
};
$(document).ready(function() {
var file = $('[name="file"]');
var imgContainer = $('#imgContainer');
$('#btnUpload').on('click', function() {
var filename = $.trim(file.val());
if (!(isJpg(filename) || isPng(filename))) {
alert('Please browse a JPG/PNG file to upload ...');
return;
}
$.ajax({
url: 'FileData.htm',
type: "POST",
data: new FormData(document.getElementById("fileForm")),
enctype: 'multipart/form-data',
processData: false,
contentType: false
}).done(function(data) {
imgContainer.html('');
var img = '<img src="data:' + data.contenttype + ';base64,'
+ data.base64 + '"/>';
imgContainer.append(img);
}).fail(function(jqXHR, textStatus) {
//alert(jqXHR.responseText);
alert('File upload failed ...');
});
});
$('#btnClear').on('click', function() {
imgContainer.html('');
file.val('');
});
});
</script>
</head>
<body>
<!-- <form name="dlgContent" action="FileData.htm" id="dlgcon" enctype="multipart/form-data" method="POST">
<input type="file" name="excelfile"/>
<input type="submit"/>
</form> -->
<div>
<form id="fileForm">
<input type="file" name="file" />
<button id="btnUpload" type="button">Upload file</button>
<button id="btnClear" type="button">Clear</button>
</form>
<div id="imgContainer"></div>
</div>
</body>
</html>
And my Controller Class in spring mapping given below
#RequestMapping(value="/FileData.htm", method = RequestMethod.POST)
public void FileData(Model model, #RequestParam CommonsMultipartFile[] excelfile, HttpServletRequest request, HttpServletResponse response){
System.out.println("bhjsbfjhsbfbdesfbsfb");
response.setContentType("application/json");
FileData fd = new FileData();
//Map<String, String> data = fd.submitFileData(excelfile);
Gson gson = new Gson();
// String values = gson.toJson(data);
try {
//response.getWriter().write(values);
//System.out.println(values);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Thanks.
Actually you are sending Json and not html you should use #ResponseBody
#RequestMapping(value="/upload", method = RequestMethod.POST)
public #ResponseBody
FileData upload(MultipartHttpServletRequest request,
#RequestParam String albumName,
HttpServletResponse response) {
Iterator<String> itr = request.getFileNames();
//others code here
Also Don't forget !! to config multipart data ,
Plus send back Object using jackson lib to jquery done function to be work
Gson lib is not good to use with #ResponseBody , we are using Gson with RestTemplate instead.
I can upload file in Java Web Application, but, if I want to send information and upload file, the system upload file and consider the information as null!
My code:
Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("information") == null)
System.out.println("information is null");
Helper helper = new Helper();
String url = "C:\\Users\\.....<private url>";
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024);
factory.setRepository(new File(url));
ServletFileUpload upload = new ServletFileUpload(factory);
try{
List<FileItem> partes = upload.parseRequest(request);
for(FileItem items: partes){
File file = new File(url,items.getName());
items.write(file);
request.getRequestDispatcher("view/upfile/upfile.jsp").forward(request, response);
return;
}
}catch(Exception e){
request.getSession().setAttribute("error", e.toString() + ": " + url);
request.getRequestDispatcher("view/excepciones/message.jsp").forward(request, response);
return;
}
}
File JSP:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Subir el archivo</h1>
<form action = "<%= request.getContextPath() %>/UpFilesController" method="post" enctype = "multipart/form-data">
<input type = "file" name = "file"/>
<input type = "text" name = "information"/>
<input type = "submit" name = "action4" value = "Subir Archivo"/>
</form>
</body>
Out of GlassFish Server:
information is null
I'm using Spring MVC 3 with Hibernate. And I'm stuck with displaying the image. I am perfectly able to upload the image but I am unable to display it after the successful upload. Please suggest me where I had stepped wrong .below is the code i am trying.
This is my controller:
private String uploadFolderPath;
ServletConfig config;
public String getUploadFolderPath() {
return uploadFolderPath;
}
public void setUploadFolderPath(String uploadFolderPath) {
this.uploadFolderPath = uploadFolderPath;
}
#RequestMapping(value = "/uploadfile",method = RequestMethod.GET)
public String getUploadForm(Model model) {
model.addAttribute(new UploadItem());
return "/uploadfile";
}
#RequestMapping(value = "/uploadfile",method = RequestMethod.POST)
public String create(UploadItem uploadItem, HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors,
HttpSession session) {
try {
MultipartFile filea = uploadItem.getFileData();
InputStream inputStream = null;
OutputStream outputStream = null;
if (filea.getSize() > 0) {
inputStream = filea.getInputStream();
// File realUpload = new File("C:/");
outputStream = new FileOutputStream("C:\\images\\"
+ filea.getOriginalFilename());
System.out.println("====22=========");
System.out.println(filea.getOriginalFilename());
System.out.println("=============");
int readBytes = 0;
byte[] buffer = new byte[8192];
while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
System.out.println("===ddd=======");
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
session.setAttribute("uploadFile", "C:\\images\\"
+ filea.getOriginalFilename());
}
} catch (Exception e) {
e.printStackTrace();
}
return "uploadfileindex";
}
#RequestMapping(value = "/uploadfileindex",method = RequestMethod.GET)
public String showRegistration(Model model) {
return "uploadfileindex";
}
// Process the form.
#RequestMapping(value = "/uploadfileindex",method = RequestMethod.POST)
public String processRegistration(BindingResult result) {
return "uploadfileindex";
uploadfile jsp
<%#page contentType="text/html;charset=UTF-8"%>
<%#page pageEncoding="UTF-8"%>
<%# page session="false"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<META http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Upload Example</title>
<script language="JavaScript">
function Validate()
{
var image =document.getElementById("image").value;
if(image!=''){
var checkimg = image.toLowerCase();
if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.jpeg|\.JPEG)$/)){
alert("Please enter Image File Extensions .jpg,.png,.jpeg");
document.getElementById("image").focus();
return false;
}
}
return true;
}
</script>
</head>
<body>
<form:form modelAttribute="uploadItem" name="frm" method="post"
enctype="multipart/form-data" onSubmit="return Validate();">
<fieldset><legend>Upload File</legend>
<table>
<tr>
<td><form:label for="fileData" path="fileData">File</form:label><br />
</td>
<td><form:input path="fileData" id="image" type="file" /></td>
</tr>
<tr>
<td><br />
</td>
<td><input type="submit" value="Upload" /></td>
</tr>
</table>
</fieldset>
</form:form>
</body>
</html>
uploadfileindex.jsp
<%#page contentType="text/html;charset=UTF-8"%>
<%#page pageEncoding="UTF-8"%>
<%# page session="true"%>
<%#taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<META http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Welcome</title>
</head>
<body>
<h2>Upload Example</h2>
<%
if (session.getAttribute("uploadFile") != null
&& !(session.getAttribute("uploadFile")).equals("")) {
%>
<h3>Uploaded File</h3>
<br>
<img src="<%=session.getAttribute("uploadFile")%>" alt="Upload Image" />
<%
session.removeAttribute("uploadFile");
}
%>
</body>
</html>
As you are saying that you have that image on your hard drive but you are not able to display it over the web page. So what you need to do is, place your image in the installation directory that is from where the MVC is installed. Like is we use an WAMP server, we store image in wamp\www\yourprojectfolder\image.jpg. Like this you'll be fetching your image directly through the web page.
#Controller
#RequestMapping(value="/imageServer")
public class ImageServer {
#RequestMapping(value="/{imageUrl:.+}")
public void getImageByUrl(#PathVariable String imageUrl,
HttpServletResponse response) throws IOException
{
String filesFolder = "C:/images";
File finalImage = new File(filesFolder+"/"+imageUrl);
FileInputStream fileStream=new FileInputStream(finalImage);
try {
response.getOutputStream().write(IOUtils.toByteArray(fileStream));
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
And on your JSP Page, go for :
<img src"${pageContext.request.contextPath}/imageServer/image.jpg">
So you can see C:/images/image.jpg in your webo page.
I am using the program from the site http://codejava.net/coding/upload-files-to-database-servlet-jsp-mysql that allows the user to upload files in the database. So far I have no troubles in inserting the data into the database.
I want to add a field named filename in the database. But I am unable to get the file name of the uploaded file. Is there a method for getting it? Or can I use BufferedReader to read the file?
FileUploadDB.java
package com.process.web.controller;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet("/fileuploaddb.html")
#MultipartConfig(maxFileSize = 16177215)
public class FileUploadDB extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
private String dbURL = "jdbc:jtds:sqlserver://localhost:1433;DatabaseName=ATS;SelectMethod=cursor;";
private String dbUser = "sa";
private String dbPass = "benilde";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// gets values of text fields
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//DriverManager.getConnection(dbURL);
//com.microsoft.sqlserver.jdbc.Driver
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
if(conn!=null) {
System.out.println("Connection Successful!");
} else {
System.out.println("Error in Connection");
}
// constructs SQL statement
String sql = "INSERT INTO contact (firstname, lastname, photo) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBinaryStream(3, filePart.getInputStream(), (int)(filePart.getSize()));
}
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
This is the upload.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="fileuploaddb.html" enctype="multipart/form-data">
<table border="0">
<tr>
<td>First Name: </td>
<td><input type="text" name="firstName" size="50"/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" name="lastName" size="50"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="50"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
**This is the Message.jsp**
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message</title>
</head>
<body>
<center>
<h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>
**On this part, the System.out.println(filePart.getName()); does not print the file
name of the selected file to be uploaded, but it prints out the word "photo".
Which is from
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Use the following method
private String getFileName(Part p){
String header=p.getHeader("content-disposition");
String filename = header.substring(header.indexOf("filename=\"")).split("\"")[1]; //getting filename
return filename;
}
The snippet is taken from my blog here
I have no troubles in inserting the data into the database but I am unable to get the file name of the uploaded file. Is there a method for getting it?
Since Servlet API 3.1, the Part interface provides the getSubmittedFileName() method which does what you need.
Gets the file name specified by the client
This class represents a part or form item that was received within a multipart/form-data POST request.
Alternatively you can use Commons Fileupload library provided by Apache that makes it easy to add robust, high-performance, file upload capability to your servlets and web applications.
Sample code:
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
}
}
Find complete code here and here