Upload and download Java files

Source: Internet
Author: User

Upload and download Java files
Basic Principles

File Upload principles
By setting the Method = "post" enctype = "multipart/form-data" attribute for the form element, the data submitted by the form is submitted in binary encoding, in the Servlet that receives this request, you can obtain the content of the uploaded file by using a binary stream to upload the file.

How files are downloaded

JSP + Servlet for file upload, download, and upload

    

@ Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System. out. println ("received requests"); // obtain the stream information from the request. InputStream fileSource = req. getInputStream (); String tempFileName = "E:/tempFile"; // tempFile points to the temporary File tempFile = new File (tempFileName ); // The output stream of the outputSteam file points to the temporary file FileOutputStream outputStream = new FileOutputStream (tempFile ); Byte B [] = new byte [1024]; int n; while (n = fileSource. read (B ))! =-1) {outputStream. write (B, 0, n);} // close the output stream and input stream outputStream. close (); fileSource. close (); // get the name of the uploaded file RandomAccessFile randomFile = new RandomAccessFile (tempFile, "r"); randomFile. readLine (); String str = randomFile. readLine (); int beginIndex = str. lastIndexOf ("\") + 1; int endIndex = str. lastIndexOf ("\" "); String filename = str. substring (beginIndex, endIndex); // locate the file pointer to the file header randomFile. seek (0 ); Long startPostion = 0; int I = 1; // get the starting position of the file content while (n = randomFile. readByte ())! =-1 & I <= 4) {if (n = '\ n') {startPostion = randomFile. getFilePointer (); I ++ ;}} startPostion = startPostion-1; // obtain the file content ending position randomFile. seek (randomFile. length (); long endPosition = randomFile. getFilePointer (); int j = 1; while (endPosition> = 0 & j <= 2) {endPosition --; randomFile. seek (endPosition); if (randomFile. readByte () = '\ n') {j ++ ;}} endPosition = endPosition-1; // you can specify the path to save the file to be uploaded. Ing realPath = getServletContext (). getRealPath ("/") + "images"; File fileupload = new File (realPath); if (! Fileupload. exists () {fileupload. mkdir ();} File saveFile = new File (realPath, filename); RandomAccessFile randomAccessFile = new RandomAccessFile (saveFile, "rw "); // read the file content from the temporary file (obtained based on the start position and end position) randomAccessFile. seek (startPostion); while (startPostion> endPosition) {randomAccessFile. write (randomFile. readByte (); startPostion = randomFile. getFilePointer ();} // close the input/output stream and delete the temporary file randomAccessFile. close (); rand OmFile. close (); tempFile. delete (); req. setAttribute ("result", "uploaded successfully! "); RequestDispatcher dispatcher = req. getRequestDispatcher (" jsp/01.jsp"); dispatcher. forward (req, resp );}
Download

Download implementation

text.txt
Package com. imooc. servlet; import java. io. file; import java. io. fileInputStream; import java. io. IOException; import java. io. inputStream; import javax. servlet. servletException; import javax. servlet. servletOutputStream; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class DownloadServlet extends HttpServlet {@ Override p Rotected void doPost (HttpServletRequest req, response resp) throws failed, IOException {doGet (req, resp) ;}@ Override protected void doGet (HttpServletRequest req, response resp) throws failed, IOException {// get the file download path String path = getServletContext (). getRealPath ("/") + "images/"; String filename = req. getParameter ("filename"); File file = new File (path + fil Ename); if (file. exists () {// set the resp type. setContentType ("application/x-msdownlaod"); // set the header information resp. setHeader ("Content-Disposition", "attachment; filename = \" "+ filename +" \ ""); InputStream inputStream = new FileInputStream (file); ServletOutputStream outputStream = resp. getOutputStream (); byte B [] = new byte [1024]; int n; while (n = inputStream. read (B ))! =-1) {outputStream. write (B, 0, n);} // close the stream and release the resource outputStream. close (); inputStream. close ();} else {req. setAttribute ("errorResult", "the file does not exist. Download failed! ");}}}
SmartUpload

Upload
Upload files as follows:

    

The process is as follows:

// Set the storage path of the uploaded File to String filePath = getServletContext (). getRealPath ("/") + "images"; file File = new File (filePath); if (! File. exists () {file. mkdir ();} SmartUpload su = new SmartUpload (); // initialize the object su. initialize (getServletConfig (), request, response); // sets the size of the uploaded file su. setMaxFileSize (1024*1024*10); // you can specify the size of all files. setTotalMaxFileSize (1024*1024*100); // you can specify the file type su. setAllowedFilesList ("txt, jpg, png, gif"); String result = "uploaded successfully"; // sets the file type to be uploaded. try {su. setDeniedFilesList ("rar, jsp, js"); // Upload File su. upload (); int count = su. save (filePath);} catch (Exception e) {e. printStackTrace (); result = "Upload Failed ";}

Exception Handling

If (e. getMessage (). indexOf ("1015 ")! =-1) {result = "Upload Failed: the file type is incorrect! ";} Else if (e. getMessage (). indexOf (" 1010 ")! =-1) {result = "Upload Failed: the file type is incorrect! ";} Else if (e. getMessage (). indexOf (" 1105 ")! =-1) {result = "Upload Failed: the size of the uploaded file is greater than the maximum size allowed! ";} Else if (e. getMessage (). indexOf (" 1110 ")! =-1) {result = "Upload Failed: the total size of the uploaded file is greater than the maximum size allowed! ";}

Use SmartUpload to obtain other attributes of the uploaded file

For (int I = 0; I <su. getFiles (). getCount (); I ++) {org. lxh. smart. file tempFile = su. getFiles (). getFile (I); System. out. println ("--------"); System. out. println ("name value in the form:" + tempFile. getFieldName (); System. out. println ("Upload File Name:" + tempFile. getFileName (); System. out. println ("Size of the uploaded file:" + tempFile. getSize (); System. out. println ("extended name of the uploaded file:" + tempFile. getFileExt (); System. out. println ("full name of the uploaded file:" + tempFile. getFilePathName (); System. out. println ("--------");}

The output result is as follows:

Name value in the form: myfile3 Upload File name: 2.png upload file size: 316681 extension name of the Upload File: png Upload File Full name: 2.png

Download

Download: img2-lg.jpg

SmartDownloadServletAs follows:

    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        String filename = req.getParameter("filename");        SmartUpload su = new SmartUpload();        su.initialize(getServletConfig(), req, resp);        su.setContentDisposition(null);        try {            su.downloadFile("/images/"+filename);        } catch (SmartUploadException e) {            e.printStackTrace();        }    }

Use SmartUpload for Batch File Download
How does one batch download files?

    

Servlet Processing

        resp.setContentType("application/x-msdownload");        resp.setHeader("Content-Disposition", "attachment;filename=test.zip");        String filepath = getServletContext().getRealPath("/")+"images/";        String[] filenames = req.getParameterValues("filename");        String str = "";        String rt = "\r\n";        ZipOutputStream zipOutputStream  = new ZipOutputStream(resp.getOutputStream());        for(String filename : filenames){            str += filename+rt;            File file = new File(filepath+filename);            zipOutputStream.putNextEntry(new ZipEntry(filename));            FileInputStream fis = new FileInputStream(file);            byte b[] = new byte[1024];            int n = 0;            while((n = fis.read(b)) != -1){                zipOutputStream.write(b, 0, n);            }            zipOutputStream.flush();            fis.close();        }        zipOutputStream.setComment("download success:"+rt+str);        zipOutputStream.flush();        zipOutputStream.close();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.