File upload Download

Source: Internet
Author: User
Tags temporary file storage

file Upload and download principle

In TCP/IP. The earliest appearing file upload download mechanism is FTP, which is the standard mechanism for files to be made available by the server.

However, in JSP programming can not use the FTP method to upload files, which is determined by the JSP execution mechanism.

Upload principle:

by setting the method= "POST" enctype= "Multippart/form-data" property for the form element, the data submitted by the form isBinary encodingof the
Way to submit. In the servlet that receives this requestBinary stream to getcontent. will be able to get the content of the uploaded file. To achieve file upload

enctype Properties:
applic ation/x-www-form-urlencoded: By default, only the Value property values in the form field are processed, and the attribute values in the form fields are processed into URL encoding.
multipart/form-data: The form processes the form data as a binary stream, and the contents of the file domain are also encapsulated in the request parameters
Text/plain: Primarily for sending mail through forms

Download principle: Step 1:httpservletresponse.setcontenttype method to set the value of the Content-type header field for the browser to handle MIME types in a way or to activate a program, such as "application/ Octet-stream "or" Application/x-msddownload "
Step 2: Pass HttpServletResponse. The SetHeader method sets the value of the content-disposition header to "attachment;filename= file name"
Step 3: Read the download file and call the Servletoutputstream object returned by the Httpservelresponse.getoutputstream method to write the contents of the attachment file to the client.


How to implement file upload download Span style= "FONT-SIZE:14PX; Background-color:rgb (255,255,255); Color:rgb (48,53,56); font-family: "microsoft yahei","hiragino Sans Gb", Helvetica, "helvetica neue", Microsoft Ya-Black, Tahoma, Arial, Sans-serif; Line-height:28px "> There are very many:

jsp+sevlet,smartupload,fileupload. Struct2

here to specify FileUpload implementation of the method of uploading and downloading.

upload:

/Set File save path string savepath = This.getservletcontext (). Getrealpath ("/web-inf/upload");

Diskfileitemfactory factory = new Diskfileitemfactory ();//disk object File File = new file (This.getservletcontext (). Getrealpath ("/web-inf/temp"));//Assume that the folder does not exist. Creates a new if (!file.exists ()) {file.mkdirs ();} Factory.setsizethreshold (1024 * 8); 8k buffer, file greater than 8K is saved to the temporary folder factory.setrepository (file);//save parsed data with temporary file servletfileupload upload = new Servletfileupload (Factory);//Declaration of the parsed Request object//inference is a normal form. Or a form with a file upload. The file Upload form value cannot be obtained directly as the normal form receives the value if (! Servletfileupload.ismultipartcontent (Request)) {return;} Upload.setfilesizemax (1024 * 1024 * 5);//Set the size of each file cannot exceed 10mupload.setsizemax (1024 * 1024 * 50);//Set the total upload file size cannot exceed 50MList <FileItem> list = upload.parserequest (request);//package each submitted form item into a listfor (Fileitem item:list) {// Inferred as normal form input field or file input field if (Item.isformfield ()) {return;} else {String filename = item.getname (); if (filename = = NULL | | filenam E.trim (). Equals ("")) {continue;} Intercept file name filename = filename.substring (filename.lastindexof ("\ \") + 1); InputStream in = Item.getinputstream ();// Prevent files from overwriting string savefilename = Makefilename (filename);//True storage path String realsavepath = Makepath (Savefilename, Savepath); String Allpath = realsavepath + "\ \" + savefilename;attach.setattachtitle (savefilename); Attach.setattachpath (AllPath) ;//inserting data into the database Attachservice.addattach (attach, Fareid); Request.setattribute ("Fareid", Fareid); FileOutputStream out = new FileOutputStream (allpath), byte buffer[] = new Byte[1024];int len = 0;while (len = in.read (Buff ER)) > 0) {out.write (buffer, 0, Len);} In.close (); Out.close (); Item.delete ();}
1.?? Why should

Factory.setrepository (New file (This.getservletcontext (). Getrealpath ("/web-inf/temp"));//Set Temporary file path

becausewhen this method is not called to set the temporary file storage folder, the default system default file path is used. Can be obtained through the system Properties Java.io.tmpdir. For example, the following code:

System.getproperty ("Java.io.tmpdir"); The Tomcat system default temporary folder is "<tomcat installation folder >/temp/".

Apache File Upload Component when parsing the contents of each field in the uploaded data, it is necessary to temporarily save the parsed data so that further processing of the data can be carried out later (either in a specific location on disk or into a database). Because the Java virtual machine can use the default memory space is limited. A "Java.lang.OutOfMemoryError" error will be thrown when the limit is exceeded.

Assume that the uploaded file is very large, such as a 800M file. The contents of the file cannot be temporarily saved in memory. The Apache file Upload component instead uses temporary files to save the data, but assuming that the uploaded file is very small, such as a 600-byte file, it is obvious that it will be better to store it directly in memory.

2. The type= "file" of the current station input will have the default button "Select Files (no files selected)" or "Browse" interface. The interface style depends on different browsers. Clicking on the button will pop up the file upload form.

download:

Bullet box: Response.setheader ("Content-disposition", "attachment;filename=" + urlencoder.encode (realname, "UTF-8");


File upload Download

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.