jsp file Upload, download

Source: Internet
Author: User

First, File upload

Uploading files is a frequently used feature in web development: for example, uploading photos in a personnel information management system based on B/s, uploading pictures in a news release system, etc... To implement the file upload function, you need to use the file input and output related classes in Java.

In TCP/IP, the first file upload mechanism that appears is FTP. It is a standard mechanism for sending files from the customer service side to the server, allowing for cross-platform text and binary format files. However, in JSP programming can not use the FTP method to upload files, which is determined by the JSP operating mechanism.

Here is the JSP page to upload the file:

[HTML]View Plaincopyprint? < param name= "allowfullscreen" value= "false" >< param name= "wmode" value= "Transparent" >
  1. <form action="file?file=upload" method="POST" enctype="Multipart/form-data " >
  2. Please select the file you want to upload:<input type="file" name= "upload" siez= "+" >< br>
  3. <input type="Submit" value= "submission">
  4. </form>
[HTML]View Plaincopyprint?

For file Upload form processing where method must be post, also add type enctype= "Multipart/form-data". This allows the data in the file to be uploaded as streaming data. Of course, no matter what the file format, can ...

The following is a servlet handler:

[Java]View Plaincopyprint?
  1. //Receive file name of temporary files in upload file contents
  2. String tempfilename = new String ("TempFileName");
  3. Tempfile object pointing to a temporary file
  4. File Tempfile = new File ("d:/" +tempfilename);
  5. OutputFile file output stream points to this temporary file
  6. FileOutputStream outputstream = new FileOutputStream (tempfile);
  7. Get all the data submitted by the client
  8. InputStream filesourcel = Request.getinputstream ();
  9. Writes the resulting client data to a temporary file
  10. byte b[] = new byte[1000];
  11. int n;
  12. while ((N=filesourcel.read (b))!=-1) {
  13. Outputstream.write (b,0,n);
  14. }
  15. Turn off the output stream and input stream
  16. Outputstream.close ();
  17. Filesourcel.close ();
  18. Randomfile object pointing to a temporary file
  19. Randomaccessfile randomfile = new Randomaccessfile (Tempfile,"R");
  20. Reads the first row of data from a temporary file
  21. Randomfile.readline ();
  22. Reads the second row of data from the temporary file, which contains the path and file name of the files
  23. String FilePath = Randomfile.readline ();
  24. Get file name
  25. int position = filepath.lastindexof (' \ \ ');
  26. Codetostring codetostring = new codetostring ();
  27. String filename = codetostring.codestring (filepath.substring (Position,filepath.length ()-1));
  28. Reposition read file pointer to file header
  29. Randomfile.seek (0);
  30. Gets the position of the four-row carriage return, which is the beginning of the upload file data
  31. Long forthenterposition = 0;
  32. int forth = 1;
  33. while ((N=randomfile.readbyte ())!=-1&& (forth<=4)) {
  34. if (n==' \ n ') {
  35. Forthenterposition = Randomfile.getfilepointer ();
  36. forth++;
  37. }
  38. }
  39. Generate directory for uploaded files
  40. File FileupLoad = new File ("D:/work space/jsp workspace/jsp_servlet_upandload/file","upLoad");
  41. Fileupload.mkdir ();
  42. The SaveFile object points to the file to be saved
  43. File SaveFile = new File ("D:/work space/jsp workspace/jsp_servlet_upandload/file/upload", filename);
  44. Randomaccessfile randomaccessfile = new Randomaccessfile (SaveFile,"RW");
  45. Find the end location of the uploaded file data, which is the fourth line
  46. Randomfile.seek (Randomfile.length ());
  47. Long endposition = Randomfile.getfilepointer ();
  48. Int j = 1;
  49. while ((endposition>=0) && (j<=4)) {
  50. endposition--;
  51. Randomfile.seek (endposition);
  52. if (randomfile.readbyte () = =' \ n ') {
  53. j + +;
  54. }
  55. }
  56. Writes data to the file to be saved from the beginning of the uploaded file data to the end location
  57. Randomfile.seek (forthenterposition);
  58. Long startPoint = Randomfile.getfilepointer ();
  59. while (startpoint<endposition) {
  60. Randomaccessfile.write (Randomfile.readbyte ());
  61. StartPoint = Randomfile.getfilepointer ();
  62. }
  63. Close file input, output
  64. Randomaccessfile.close ();
  65. Randomfile.close ();
  66. Tempfile.delete ();

where the Codetostring () method is a Chinese character processing method. If the file does not encode the conversion, the uploaded file name will be garbled, the received data will be garbled:

Here is the codetostring () source code:

[Java]View Plaincopyprint?
  1. Functions for handling Chinese strings
  2. Public string codestring (String str) {
  3. String s = str;
  4. try {
  5. byte[] temp = s.getbytes ("Utf-8");
  6. s = new String (temp);
  7. return s;
  8. } catch (Unsupportedencodingexception e) {
  9. E.printstacktrace ();
  10. return s;
  11. }
  12. }

Two: File download the simplest way to implement a file download is to use a hyperlink. Suppose User.doc This document exists in the upload subdirectory of the Web directory on the server. Such as:

[Java]View Plaincopyprint?
    1. <a href="Http://localhost:8080/upload/user.doc" > Download user.doc</a>

When you click the hyperlink, the document opens directly in the browser, as if you were embedding the word software in a browser.

When you open a document, you can save it. Of course, on the web, the most common way is when you click the link and the Save As dialog box appears:

[Java]View Plaincopyprint?
  1. Get the file name to download
  2. String filename = request.getparameter ("name");
  3. //Get the output stream to the customer
  4. OutputStream outputstream = Response.getoutputstream ();
  5. //output file with byte array, send 600 bytes to the output stream at a time
  6. byte b[] = new byte[600];
  7. //files to download
  8. File Fileload = new File ("D:/work space/jsp workspace/jsp_servlet_upandload/file/upload", filename);
  9. //client Use the Save File dialog box
  10. Response.setheader ("content-disposition", "attachment;filename=" +filename);
  11. //Notify the MIME type of the customer service file
  12. Response.setcontenttype ("Application/msword");
  13. //Inform the length of customer service file
  14. Long filelength = Fileload.length ();
  15. String length = string.valueof (filelength);
  16. Response.setheader ("content_length", length);
  17. //Read files, and send to the customer service side download
  18. FileInputStream InputStream = new FileInputStream (fileload);
  19. int n = 0;
  20. While ((N=inputstream.read (b))!=-1) {
  21. Outputstream.write (b,0,n);
  22. }

         in this program, the setContentType () of the response object defines the MIME type that the server sends to the client side of the content. This is not a special introduction to MIME. In fact, all resources that the browser can handle have a corresponding MIME resource type. In the interaction with the server, the browser opens it directly to the HTML, JSP, and other file browsers. The appropriate method is called for files that cannot be opened by browsers such as Word, Excel, and so on. For files that do not have a tag MIME type. The browser guesses its type based on its extension and file content ...

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.