3a. Create a servlet application to upload and download a file.

****** Download *****



package servlet;


import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "FileDownloadServlet", urlPatterns = {"/FileDownloadServlet"})
public class FileDownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String fileToDownload = request.getParameter("filename");
        System.err.println("Downloading file now...");
        downloadFile(request, response, fileToDownload);
    }
   
    private void downloadFile(HttpServletRequest request, HttpServletResponse response, String fileName) throws ServletException, IOException {
        int lenght = 0;
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            ServletContext context = getServletConfig().getServletContext();
            response.setContentType((context.getMimeType(fileName) != null) ? context.getMimeType(fileName) : "application/pdf");

            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName);
            InputStream inputStream = context.getResourceAsStream("/" + fileName);
            byte[] bytes = new byte[1024];
           
            while((inputStream != null) && ((lenght = inputStream.read(bytes)) != -1)) {
                outputStream.write(bytes, 0, lenght);
            }
            outputStream.flush();
        }
    }
}





***** Upload *****


<h1>File Upload Application</h1>
        <form action="FileUploadServlet" enctype="multipart/form-data" method="POST">
            File: <input type="file" name="file" id="file"/><br/><br/>
            Destination: <input type="text" value="" name="destination" /><br/><br/>
            <input type="submit" value="Upload File" name="upload" id="upload"/>
        </form>








*****FileUploadServlet.java*****


package servlet;



import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
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(urlPatterns = {"/FileUploadServlet"})

@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        final String path = request.getParameter("destination");
        final Part filePart = request.getPart("file");
        final String fileName = retrieveFileName(filePart);

        OutputStream out = null;
        InputStream filecontent = null;
        final PrintWriter writer = response.getWriter()

        try {
            out = new FileOutputStream(new File(path + 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);
            }
            response.sendRedirect("SucessfulUploadServlet");
        } catch (FileNotFoundException fne) {
            writer.println("You either did not specify a file to upload or are trying to upload a file to a protected or nonexistent location.");
            writer.println("<br/> ERROR: " + fne.getMessage());
        } finally {
            if (out != null)
                out.close();

            if (filecontent != null)
                filecontent.close();
            if (writer != null)
                writer.close();
        }
    }

    private String retrieveFileName(final Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
}



Comments

  1. You made some good points there. I did a search on the topic and found most people will agree with your blog.Otherwise any one who want to learn java core to advance contact us on 9311002620 or visit our further websites;- https://htsindia.com/Courses/java/core-java-training-course-institute

    ReplyDelete
  2. Thank you for sharing this post its very knowledgeable i hope that you will continue to post these kinds of contents in future apart from that if anyone looking for Advance Excel institute in delhi so Contact Here-+91-9311002620 Or Visit Website- https://www.htsindia.com/Courses/business-analytics/adv-excel-training-course

    ReplyDelete
  3. Here all content so useful and helpful for beginner and experience both.This site is so amazing, This sites gives good knowledge of advance-java-training,This is very helpful for me.

    ReplyDelete

Post a Comment