J2EE file upload and download summary, j2ee File Upload Summary

Source: Internet
Author: User

J2EE file upload and download summary, j2ee File Upload Summary
I. File Upload

Upload process:

1. upload files on jsp pages

2. Obtain the file stream in the background (the principles are the same and the implementation methods are different.

Sevelet is generally obtained from HttpServletRequest using ServletFileUpload;

Struts2 will automatically encapsulate the File stream as a File object; springmvc will be MultipartFile)

3. Obtain the output stream and generate a file in the corresponding directory.

The following is a simple example based on the previous project.

The front-end jsp upload code will not be mentioned. If you use form, enctype = "multipart/form-data" should not be lost.

Because files need to be uploaded in multiple projects, I usually create a file processing class for the upload code, and the upload address is configured in the configuration file. The Code is as follows:

/*** Obtain the corresponding value based on the key of the configuration file * @ param key * @ return */public static String getPropertyValue (String key) {Properties props = new Properties (); inputStream in = null; in = FileTools. class. getClassLoader (). getResourceAsStream ("config. properties "); try {props. load (in); in. close ();} catch (FileNotFoundException e1) {e1.printStackTrace ();} catch (IOException e1) {e1.printStackTrace ();} return props. getP Roperty (key );} /*** upload a single file ** @ param uploadFile the file to be uploaded * @ param uploadFileName the name of the file to be uploaded * @ param uploadPath the address for storing the uploaded file * @ return */public static ResponseJson uploadFile (File uploadFile, string uploadFileName, String uploadPath) {ResponseJson responseJson = new ResponseJson (); Result result = new Result (); boolean success = false; if (uploadPath = null) {// if the server is linux, you need to change it to filePathForLinux String OS = IpUtils. getOSName (); if (OS. startsWith ("linux") | OS. startsWith ("Linux") {uploadPath = getPropertyValue ("filePathForLinux");} else {uploadPath = getPropertyValue ("filePath");} uploadPath = uploadPath + File. separator + DateUtils. getYMD (); System. out. println ("temporary name of the uploaded file:" + uploadFile. getName (); System. out. println ("file name:" + uploadFileName); System. out. println ("file storage address:" + uploadPath); // view the file size I F (uploadFile. length () <= 0) {result. setMsg ("uploaded files are empty Files");} else if (uploadFile. length ()> 0 & uploadFile. length () <153600000) {File file1 = new File (uploadPath), uploadFileName); if (file1.exists () {result. setMsg ("a File with the same name already exists");} else {File dir = new File (uploadPath); if (! (Dir. exists () dir. mkdirs (); // upload the file try {FileUtils. copyFile (uploadFile, file1); result. setMsg ("File Uploaded successfully"); success = true;} catch (IOException e) {e. printStackTrace (); result. setMsg ("the file is not saved successfully") ;}} else {result. setMsg ("the uploaded file is greater than 50 MB");} result. setSuccess (success); result. setName (uploadFileName); responseJson. setFilePath (uploadPath); responseJson. setSuccess (success); responseJson. setResult (result); return responseJson ;}
Code
// If the server is linux, you need to change it to filePathForLinux String OS = IpUtils. getOSName (); if (OS. startsWith ("linux") | OS. startsWith ("Linux") {uploadPath = getPropertyValue ("filePathForLinux");} else {uploadPath = getPropertyValue ("filePath ");}

Explanation:

A>. This part is mainly because the upload path I developed and tested in windows is different from that in linux (because I use absolute paths ),

If this is not the case, the path will go wrong after the development and deployment to the server. So I will first determine the current system and then call the corresponding upload directory of the system.

B>. in addition, you need to determine the file type, file size, and so on for file upload. However, I personally think that it is best to make a judgment on the front-end. The purpose of this judgment is to prevent unreasonable files from being uploaded to the background, right?

If you judge in the background, all your files will be uploaded to the background. Isn't it too late? It's nothing more than the difference between saving and not saving.

Ii. File Download

The download logic is a little more complex than the upload logic. The process is as follows:

1. Read the path of the file to be downloaded.

2. Get the file input stream (get the input stream from the file to be downloaded)

3. Set the file output stream (that is, set HttpServletResponse ).

4. Core: Read files from the input stream and generate files from the output stream.

The sample code is as follows:

/*** Download a single file ** @ param response * @ param filePath the address for saving the downloaded file * @ param fileName The Name Of The downloaded file * @ return * @ throws Exception */public static Result downloadFile (HttpServletResponse response, string filePath, String fileName) throws Exception {Result result = new Result (); result. setSuccess (false); if ("". equals (filePath) | null = filePath) {result. setMsg ("File path exception");} else {// file File = new File (filepath); Syste M. out. println ("------- start to download --------" + fileName); File file = new File (filePath, fileName); if (file. exists () {response. setHeader ("Content-Type", "application/force-download"); // transcode the file name so that the frontend can display the Chinese name response. setHeader ("Content-Disposition", "attachment; filename = \" "+ new String (fileName. getBytes ("gb2312"), "ISO8859-1") + "\" "); ServletOutputStream OS = response. getOutputStream (); BufferedInputStream fin = New BufferedInputStream (new FileInputStream (file); try {byte [] content = new byte [1024]; int length; while (length = fin. read (content, 0, content. length ))! =-1) {OS. write (content, 0, length);} result. setSuccess (true);} catch (Exception e) {System. out. println ("File Download failed"); result. setMsg ("File Download failed");} finally {fin. close (); OS. flush (); OS. close () ;}} else {System. out. println ("the file to be downloaded does not exist"); result. setMsg ("the object to be downloaded does not exist") ;}} return result ;}
Explanation:

A>. Here, the returned Result message class is customized to encapsulate the information returned by the download operation.

B>. Of course, the setting of the response header is not unique and the best one for you.

C>. garbled characters may occur during file downloading. It is nothing more than confusion in character sets, so you can solve it with patience.


Well, the summary is here.

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.