How does one upload files in Java?
I have an Apache Tomcat webserver. I need a simple code that can be used from Java desktop app and Servlet web app. My assignment requires me to make a simple document upload and management system in both desktop (Java) and web (JSP/Servlet) app.
The database part I made and almost all logic part but uploading a file is something I don't know.
What I need is something that works in desktop and web logic part, so I can reuse it.
Sorry for asking so bluntly but I'm kind of in a hurry and I'm stuck. Without file upload I have nothing.
2 replies to this topic
#1
Posted 20 June 2011 - 12:12 PM
|
|
|
#2
Posted 20 June 2011 - 05:38 PM
simple codeI don't think simple codes exist to upload files to server without downloading certain libraries.
Let me google that for you
There are some libraries out there that make this task simple though.
#3
Posted 21 June 2011 - 08:06 AM
Example with an image:
Some jsp:
Works for me (netbeans + glassfish)
Some jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Hello World!</h1> <form METHOD="POST" ENCTYPE="multipart/form-data" action="fileServlet.do"> <input type="file" name="file"/><br/> <input type="submit" value="submit"/> </form> </body> </html>Some servlet:
package servlet;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage img = ImageIO.read(request.getPart("file").getInputStream());
File file = new File("location\location\name.extension");
file.createNewFile();
ImageIO.write(img, "png", file);
}
}
Servlet mapping:<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/...web-app_3_0.xsd"> <servlet> <servlet-name>FileServlet</servlet-name> <servlet-class>servlet.FileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileServlet</servlet-name> <url-pattern>/fileServlet.do</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> </web-app>
Works for me (netbeans + glassfish)
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account


Back to top









