File upload to Weblogic server failed - forms

I am trying to upload a file to WebLogic server using servlets. This is the doPost method:
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException
{
boolean isMultipart;
String filePath=null;
int maxFileSize = 2 * 1024 * 1024;
int maxMemSize = 1024 * 1024;
File file ;
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart )
{
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>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(2 * 1024 * 1024);
// 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();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
ServletContext context = getServletContext();
Connection conn = (Connection)context.getAttribute("DBCON");
PreparedStatement stmt=null;
try
{
stmt=conn.prepareStatement("INSERT INTO emp VALUES(?, ?, ?)");
out.println("Created the statement!");
}
catch (SQLException e)
{
out.println("Unable to create prepared statement because: "+e.getMessage());
}
WriteToDB ob=new WriteToDB();
out.println("CWriting to DB!");
ob.process("C:\\JDeveloper\\mywork\\App\\Project1\\data" + "\\" + fileName, stmt, out);
out.println("Wrote to DB!");
}
}
} catch (FileUploadException e) {
}
out.println("</body>");
out.println("</html>");
}
And this is, as I've read, the important part of web.xml:
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
C:\JDeveloper\mywork\App\Project1\data
</param-value>
I am using JDeveloper.
I have a standard upload HTML page with form data.
Everything is fine, except that the file is not to be found at the stored location, and it throws that exception.
Please help, thank you.

Related

how to get file content from file using gwtupload

i am using GWTUpload to upload a file.
i am getting the server info, file name, content type etc.. in onFinishHandler, but there's no option to get the file content from server to client.
Note : am trying to upload XML File and EXCEL File
i am using GWT 2.4, GXT 3.0.1, GWTUpload 0.6.6
here's the sample code
Client Code - OnFinishHandler
u.addOnFinishUploadHandler(new OnFinishUploaderHandler() {
#Override
public void onFinish(IUploader uploader) {
if (uploader.getStatus() == Status.SUCCESS) {
System.err.println(uploader.getServerResponse());
UploadedInfo info = uploader.getServerInfo();
System.out.println("File name " + info.name);
System.out.println("File content-type " + info.ctype);
System.out.println("File size " + info.size);
System.out.println("Server message " + info.message);
}
}
});
Servlet Code
public class GWTFileUploadServlet extends UploadAction {
private static final long serialVersionUID = -6742854283091447922L;
String fileContent;
File uploadedFile;
#Override
public String executeAction(HttpServletRequest request,
List<FileItem> sessionFiles) throws UploadActionException {
String response = "";
int cont = 0;
for (FileItem item : sessionFiles) {
if (false == item.isFormField()) {
cont++;
try {
File file = File.createTempFile("upload-", ".bin");
item.write(file);
uploadedFile = file;
fileContent = item.getContentType();
response += "File saved as " + file.getAbsolutePath();
} catch (Exception e) {
throw new UploadActionException(e.getMessage());
}
}
}
removeSessionFileItems(request);
return response;
}
#Override
public void getUploadedFile(HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (fileContent != null && !fileContent.isEmpty()) {
response.setContentType(fileContent);
FileInputStream is = new FileInputStream(uploadedFile);
copyFromInputStreamToOutputStream(is, response.getOutputStream());
} else {
renderXmlResponse(request, response, XML_ERROR_ITEM_NOT_FOUND);
}
}
}
please help me....
You can read the file you have created in the filesystem when you called item.write(...), but it is better if you get an InputStream from the FileItem you received and write its content anywhere. For instance if the content is a String you can use a StringWritter to get it:
InputStream inputStream = item.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer);
String theContentString = writer.toString();
[EDITED]
To get the content of the file in client side, so you have to retrieve it from the server using any method:
As as a customized message in your gwtupload servlet if the content of the file is ascii: use return String of executeAction.
Do a RequestBuilder call to the servlet to get the file using the uploader url value.
Use any GWT ajax mechanism like RPC.
In modern browsers you can get the content of a file in client side without sending it to server side. Take a look to lib-gwt-file
In your code You can just use
byte[] file ;
file = item.get();
And You will get all the file content in an encoded format in the "file" variable .

download file from url in gwt

I want to download a file from internet and I have url of that file . so I wrote a download servlet :
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String pathToDownload = request.getParameter("url");
URL url = new URL(pathToDownload);
URLConnection uc = url.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
InputStream is = uc.getInputStream();
response.setContentType(contentType);
// resp.setHeader("Content-Disposition", "attachment; filename*=\"utf-8''" + filename + "");
ServletOutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
in this i want to show the popup when user clicks on file whether to save or not so there is
resp.setHeader("Content-Disposition", "attachment; filename*=\"utf-8''" + filename + "");
but I want the filename same as filename on internate so additionally what is needed in above snippet?
Cut substring from the last "/" to the end of the URL string - this is your file name.
String disposition = httpConn.getHeaderField("Content-Disposition");
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index != 0) {
fileName = disposition.substring(index + 9,
disposition.length());
}
} else {
// extracts file name from URL
fileName = link.substring(link.lastIndexOf("/") + 1,
link.length());
}

Send a file from server to client in GWT

I am using GWT.
I have to download a file file from server to client.
Document is in the external repository.
Client sends the id of the document through a Servlet.
On server side: Using this ID document is retrieved:
Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();
int c;
while ((c = inputStream.read()) != -1) {
System.out.print((char) c);
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();
Here I can read the document.
I want to send this to the client.
How do I make this a file and send it back to the client?
In Your Servlet:
Document document =(Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
String name = contentStream.getFileName();
response.setHeader("Content-Type", "application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
OutputStream os = response.getOutputStream();
InputStream is =
(ByteArrayInputStream) contentStream.getStream();
BufferedInputStream buf = new BufferedInputStream(is);
int readBytes=0;
while((readBytes=buf.read())!=-1) {
os.write(readBytes);
}
os.flush();
os.close();// *important*
return;
You can create a standard servlet (which extends HttpServlet and not RemoteServiceServlet) on server side and opportunity to submit the id as servlet parameter on client side.
Now you need after getting request create the excel file and send it to the client. Browser shows automatically popup with download dialog box.
But you should make sure that you set the right content-type response headers. This header will instruct the browser which type of file is it.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileId = reguest.getParameter("fileId"); // value of file id from request
File file = CreatorExel.getFile(fileId); // your method to create file from helper class
// setting response headers
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", file.length());
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
input = new BufferedInputStream(fileInput);
output = new BufferedOutputStream(outputStream);
int count;
byte[] buffer = new byte[8192]; // buffer size is 512*16
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ex) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException ex) {
}
}
}

Servlet call hanging when using S3 Java SDK

I have this servlet I call using GWT FileUpload (I don't thing it matters so much that it is GWT):
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
try {
User user = ServerUtil.validateUser(request);
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String saveFile = item.getName();
InputStream stream = item.openStream();
// Process the input stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
int maxFileSize = 10 * (1024 * 1024); //10 megs max
if (out.size() > maxFileSize) {
throw new RuntimeException("File is > than " + maxFileSize);
}
// save file data
String fileName = user.getUsername() + "_" + new Date().getTime() + "_" + saveFile;
// store to S3
String imageUrl = S3PhotoUtil.storeThumbnailImage(out.toByteArray(), fileName, 100);
// return the url of the file
writer.println(imageUrl);
response.flushBuffer();
return;
}
} catch (RuntimeException e) {
writer.println(("error=" + e.getMessage()).getBytes());
} catch (FileUploadException e) {
writer.println(("error=Could not read file").getBytes());
} catch(IOException e) {
writer.println(("error=Image type not supported!").getBytes());
}
} catch (EIException e) {
e.printStackTrace();
writer.println(("error=Not logged in").getBytes());
}
}
When called the POST hangs, I check on firebug, it looks like it never gets a response. If I debug I see that all instructions are executed without any problem and the method is ran fine. The files are stored on my S3 bucket.
Now if I remove the call relating to the S3 storage it stops hanging, although obviously it doesn't do anything anymore... My conclusion is that there is something in this S3 storage that messes up with my servlet. The code itself is taken from the travel log example application # http://aws.amazon.com/code/1264287584622066
It does say needs tomcat and I'm using jetty... could that be a problem?
Thanks,
Thomas

save an uploaded file with GWT

I am using org.apache.commons.fileupload to upload.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
GWT.log("is multipart? " + Boolean.toString(isMultipart), null);
ServletFileUpload upload = new ServletFileUpload();
try{
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream() ;
/**
* Save th uploaded file
*/
}
}
catch(Exception e){
e.printStackTrace();
}
}
How can I save the uploaded file?
This looks like server-side code, which (aside from GWT-RPC servlets) is not specific to GWT at all. That GWT.log() is unnecessary -- replace it with a regular logging call, and handle the upload as you normally would in non-GWT code, since that's what it is.
Here is a helpful example of using apache's fileupload to get you started.
I think this can help you.
if (!item.isFormField()) {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
File saveTo = new File("/file_uploads/" + fileName);
try {
item.write(saveTo);
...
}
catch (Exception e){
...
}
Keep in mind that uploaded file may already be automatically saved by org.apache.commons.fileupload
You can set size threshold for file to be saved on disk or loaded in memory using
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(yourMaxMemorySize);
factory.setRepository(yourTempDirectory);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(yourMaxRequestSize);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
Everything you need to know about org.apache.commons.fileupload is here: Using FileUpload