Home » questions » can u give me the java code to upload and download a file to and from the webserver.?

can u give me the java code to upload and download a file to and from the webserver.?

2006-08-11 04:06:35, Category: Programming & Design
servlet or jsp

Answers

  1. fang

    On 2006-08-11 05:50:22


    check out this site:
  2. sonfarx

    On 2006-08-11 19:53:21


    Put this into your servlet for download files: String afile = request.getParameter("file"); String dir = "Full_path" File f = new Fil(dir+afile); response.setContentType("application/download"); response.setHeader("Content-Disposition", "attachment; filename= \""+afile+"\""); FileInputStream fin = new FileInputStream(f); int size = fin.available(); response.setContentLength(size); byte[] ab = new byte[size]; OutputStream os = response.getOutputStream(); int bytesread; do{ bytesread = fin.read(ab,0,size); if(bytesread >-1) os.write(ab,0,bytesread ); }while(bytesread >-1); fin.close(); os.flush(); os.close(); Your jsp or html must call this servlet with a parameter name as "file", and its parameter value like the file's name or full path of the file. If you want to upload i suggest you to download cos-05Nov2002.zip from http://www.servlets.com/cos/ You can create a servlet that use MultiparRequest class (it is into such zip) to upload files and you must define its classpath too. The servlet must be something like this: try { if(request.getContentLength()<=size) { MultipartRequest mpr = new MultipartRequest(request,"MyDirPath",size); } else // File too large } catch(IOException ioe){ // something here } Your jsp or html, to upload files, must be something like this:
    File to upload:

    Hope my explanation was good enough Goo luck!