First, let me introduce the relevant technologies :
Two important parameters in the service method.
ServletRequest uses it to receive user requests, and its function is:
One of its subinterfaces: javax.servlet.http.HttpServletRequest
ServletResponse is used to return data to the user.
One of its subinterfaces: javax.servlet.http.HttpServletResponse
File download technology:
File download technology is relatively simple to file upload technology. Let's take downloading pictures as an example:
Browse the pictures first and then download them
1. Front-end code:
<span style="font-size:14px;"><a href="img">Find all pictures under the folder</a><br/></span>
The front desk can be done in just one sentence. Directly search for background programs through web.xml
2. Background display code:
<span style="font-size:14px;">public class ShowImg extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) t ServletException, IOException { <span style="white-space:pre"> </span> doPost(request, response);//To prevent exceptions, connect doGet and doPost together}</span> <span style="font-size:14px;">public void doPost(HttpServletRequest request, Htt pServletResponse response) throws ServletException , IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.get Writer();</span> <pre name="code "><span style="font-size:14px;">//<span style="white-space:pre"> </span>Call out the Servletcontext, of course, you can also call it directly---when listed one by one The absolute path to the file is required when the picture is used</span> ServletContext context =getServletContext();String path=context.getRealPath("/imgs");//Find the absolute path of the folder File file =new File(path); <span style="font-s ize:14px;" >//<span style="white-space:pre"> </span>After finding the folder, list all images for users to browse String files[] =file.list(); for(String fn:files){ </span> <pre name="code"><span style="font-size:14px;">//Show all of them</span> String img="<img src='imgs/"+fn+"'/>";
// out.print("<a href=imgs/'"+fn+"'>Download picture</a>");String str="<a href='down?name=imgs/"+fn+"'> Download the picture</a>";// Provide the hyperlink for download, pass the parameter---Transfer the file name to the user link content and write out.print(str);out.print(img+"<br/>"); }}
3. Specific download of files
First, the corresponding protocol must be set. The download protocol requires setting the corresponding download header
<span style="white-space:pre"> </span><span style="font-size:18px;"><strong>response.setContentType("application/force-download"</strong>) ;/ /Set the corresponding header</span> When downloading, you need to display the file name of the current picture. You need to obtain it from the front desk and write it to the front desk after downloading.
<span style="font-size:18px;"> <span style="white-space:pre"> </span>OutputStream out=response.getOutputStream();//Get the output stream String name=reque st.getParameter( "name");//The parameter name passed from the client service is int num=name.lastIndexOf("/"); String aa=name.substring(num+1); aa=URLEncoder.encode(aa, "UTF- 8");//If Chinese needs to be recoded//System.out.println(aa); response.setHeader("Content-Disposition",<span style="color:#ff0000;">"<strong>attachment; filename</strong></span>='"+aa+"'");//Get the file name transmitted from there to facilitate the download of the username when storing</span> Make a specific download
<span style="font-size:18px;"> String filename=this.getServletContext().getRealPath(name);//Get the absolute path, pass the file name, and at the same time, pass the absolute path that can be obtained and you can read it InputStream in=new FileInputStream(filename); byte[] b=new byte[1024]; int len=0; while((len=in.read(b))!=-1){ out.write( b, 0, len); }</span> Reproduction image:
The rendering after clicking:
The file name is different
File upload technology
It will be very troublesome to upload files yourself, so we can use someone else's package to download the link and click to open the link form:
The client must use the multipart/form-data data type to represent the composite data type when sending HTTP.
That is: <form enctype="multipart/form-data">
Use the <input type="file" name="somename"/> html tag in the form.
Package required:
Commons-fileupload.jar, the core file upload tool is in this package.
commons-io.jar package required to upload files
Detailed explanation:
DiskFileItemFactory - Create a time-monitoring file directory, which refers to the cache area size
ServletFileUpload is used to parse HttpServletRequest. Returns a set of file objects.
FileItem represents each file object uploaded by the user.
Main process:
File f = new File("F:/ex/temp");//Specify the temporary file storage location
DiskFileItemFactory ff = new DiskFileItemFactory(1024*1024*5, f);//The size and storage location of temporary files
ServletFileUpload sf =new ServletFileUpload(ff);
List<FileItem> list=sf.parseRequest(request);//Start parsing
for(FileItem it:list){//Get the file name. And use uuid to solve the problem of duplicate names
FileUtils.copyInputStreamToFile(it.getInputStream(), new File(path+"/"+filename));//In the specified folder written
}
1. Front desk code:
<span style="font-size:18px;"><h2>Upload file</h2> <form action="UpFile" method="post" <span style="color:#ff0000;">enctype="multipart /form-data"</span> >//It must be written, otherwise the station cannot receive data<!-- This enctype="multipart/form-data"---> File1<input type="file" <span style="color:#ff6666;"> name</span>="file"/><br/> Please enter a name: <input type="text" <span style="color:#ff6666;"> name</span>="desc"/><br/> File2<input type="file"<span style="color:#ff6666;"> name</span>="file"/><br/> Please enter a name: <input type="text"<span style="color:#ff0000;"> name</span>="desc"/><br/> <input type="submit" value="Submit" /> </form></span>
2. Background code:
2-1 First create a hard disk-based factory to store temporary files
//Specify the temporary storage location File f = new File("F:/ex/temp");//Specify the temporary storage location DiskFileItemFactory ff = new DiskFileItemFactory(1024*1024*5, f);//Size of the temporary file and storage location2-2 Create a ServletFileUpload object and set the file size to maximize the file transfer
//Create an object for parsing ServletFileUpload sf =new ServletFileUpload(ff); sf.setFileSizeMax(1024*1024*10);// Only allow a single storage location to be the maximum value is 10M sf.setSizeMax(1024*102 4*20); //The maximum value of all files is 20M String path = this.getServletContext().getRealPath("/imgs"); System.out.println("Storage path: "+path); 2-3 Start parsing the object
<span style="white-space:pre"> </span>List<FileItem> list=sf.parseRequest(request);//Get all information transmitted from the front desk, the front desk must fill in enctype="multipart/form- data" for(FileItem it:list){ it0=it; //<span style="white-space:pre"> </span>If it is a normal form object--you can directly judge if(it.isFormField()) {//It is a normal form item, such as type=text name value String name=it.getString("utf-8"); System.out.println("Basic form item name:"+name);//Below The name of the explanation written}else{ <span style="white-space:pre"> </span>// This is the file name selected by the front desk String name=it.getName();//The specific file path-- -Absolute path // String str=it.getString();// Contents in the file // System.out.println("str"+str); String contenttype=it.getContentType(); Long size=it.getSiz e (); <span style="white-space:pre"> </span>System.out.println(name+","+contenttype+","+size); <pre name="code" style="font- size: 18px;">//<span style="white-space:pre"> </span>The resource file name on the server side cannot be in Chinese, the browser will automatically encode it --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The uploaded file name is converted into a name without Chinese storage. //In order to allow the user to restore the original name when downloading, the corresponding relationship between the original file name and the mapping name must be stored, and then converted back when the user downloads. //The map name String id=UUID.randomUUID().toString().replace("-", "");//The world's only UUId is used for //File name String lastname=name.substring(name.lastIndexOf(" ."));//File format//Name file formats are all found---Combination String filename =id+lastname;//New file name//Copy stream. Let it write to the corresponding location FileUtils.copyInputStreamToFile(it.getInputStream(), new File(path+"/"+filename));//path is the absolute path of the storage--defined previous}
This can achieve simple uploads, but this kind of upload is not safe at all. The complete code is attached with minor problems to prevent general problems.
After selecting the file
Check the files in the web server img, the file has been uploaded to the page "File name generated by uuid"
File upload source code:
<span style="font-size:14px;">package cn.hncu.UPfile;import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java va.io.Writer; import java .util.List; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpS ervletRequest; import javax.servlet.http.HttpServletResponse; import org.apache .commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileIte mFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons .io.FileUtils; public class MyupFile extends HttpServlet { <span style="white-space: pre;"> </span>//doGET prevents people from entering addresses in the user column. No response <span style="white-space: pre;"> </span>@Override <span style="white-space: pre;"> </span>protected void doGet(HttpServletRequest req, Http ServletResponse resp) <span style="white-space: pre;"> </span>throws ServletException, IOException { <span style="white-space: pre;"> </span>resp.setContentType("utf-8" ); <span style="white-space: pre;"> </span>Writer wr=resp.getWriter(); <span style="white-space: pre;"> </span>wr.write("This is not supported yet Upload method"); <span style="white-space: pre;"> </span>} <span style="white-space: pre;"> </span> <span style="white-space: pre ;"> </span>public void doPost(HttpServletRequest request, HttpServletResponse response) <span style="white-space: pre;"> </span>throws ServletException , IOException { <span style="white-space: pre; "> </span>request.setCharacterEncoding("utf-8"); <span style="white-space: pre;"> </span>response.setContentType("text/html;charset=utf- 8") ; <span style="white-space: pre;"> </span>PrintWriter out=response.getWriter(); <span style="white-space: pre;"> </span>//Protect to normal forms Upload method 1: <span style="white-space: pre;"> </span>//Return value GET (null) POST1(apllication/x-form-urlencoded, normal form) POST2(file: multipart/form- data, file upload form) //<span style="white-space: pre;"> </span>String type =request.getContentType(); //<span style="white-space: pre;"> < /span>if(!type.contains("mulitpart/form-data")){ //<span style="white-space: pre;"> </span>out.write("Do not support upload of normal forms 2"); //<span style="white-space: pre;"> </span>return ; //<span style="white-space: pre;"> </span>} <span style=" white-space: pre;"> </span>// Method 2<span style="white-space: pre;"> </span>boolean boo=ServletFileUpload.isMultipartContent(request); <span style=" white- space: pre;"> </span>if(boo==false){ <span style="white-space: pre;"> </span>out.print("Upload 1 of normal forms is not supported"); <span style="white-space: pre;"> </span> <span style="white-space: pre;"> </span>} <span style="white-space: pre;"> </span>} span> <span style="white-space: pre;"> </span>//Specify temporary storage location<span style="white-space: pre;"> </span>File f = new File("F :/ex/temp");//Specify the temporary file storage location <span style="white-space: pre;"> </span>DiskFileItemFactory ff =new DiskFileItemFactory(1024*1024*5, f);//Temporary File size and storage location<span style="white-space: pre;"> </span> <span style="white-space: pre;"> </span>//Create an object for parsing<span style="white-space: pre;"> </span>ServletFileUpload sf =new ServletFileUpload(ff); <span style="white-space: pre;"> </span>sf.setFileSizeMax( 1024*1024*10 );//The maximum value of only a single storage location is 10M <span style="white-space: pre;"> </span>sf.setSizeMax(1024*1024*20);//The maximum value of all files is 20M <span style="white-space: pre;"> </span>String path =this.getServletContext().getRealPath("/imgs"); <span style="white-space: pre;"> </span >System.out.println("Storage path: "+path); <span style="white-space: pre;"> </span>//Start parsing<span style="white-space: pre;" > </span>FileItem it0=null;// Used to delete temporary files in finally <span style="white-space: pre;"> </span>try { <span style="white-space: pre ;"> </span>List<FileItem> list=sf.parseRequest(request);//Get all information transmitted from the front desk, the front desk must fill in enctype="multipart/form-data" <span style="white- space: pre;"> </span>for(FileItem it:list){ <span style="white-space: pre;"> </span>it0=it; <span style="white-space: pre; "> </span>if(it.isFormField()){//is a normal form item, such as type=text value of name<span style="white-space: pre;"> </span>String name= it.getString("utf-8"); <span style="white-space: pre;"> </span>System.out.println("Basic form item name:"+name);//written below The name of the explanation is <span style="white-space: pre;"> </span>}else{ <span style="white-space: pre;"> </span>String name=it.getName();/ /Specific file path//<span style="white-space: pre;"> </span>String n1=it.getFieldName(); //<span style="white-space: pre;"> </ span>String str=it.getString();//The content in the file//<span style="white-space: pre;"> </span>System.out.println("str"+str); / /<span style="white-space: pre;"> </span>System.out.println("n1:"+n1); <span style="white-space: pre;"> </span>String contenttype=it.getContentType(); <span style="white-space: pre;"> </span>Long size=it.getSize(); <span style="white-space: pre;"> </span >//Prevent the file from empty <span style="white-space: pre;"> </span>if(size==0){ <span style="white-space: pre;"> </span>continue ;//The file is empty, return directly; <span style="white-space: pre;"> </span>} <span style="white-space: pre;"> </span>//User name. You must fill in <span style="white-space: pre;"> </span>if(name==null||name.trim()==""){ <span style="white-space: pre; "> </span>continue; <span style="white-space: pre;"> </span>} <span style="white-space: pre;"> </span>//<span style=" white-space: pre;"> </span>System.out.println(name+","+contenttype+","+size); <span style="white-space: pre;"> </span>// The resource file name on the server side cannot be in Chinese, the browser will automatically encode it -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > </span>//In order to allow users to restore their original name when downloading, they must store the correspondence between the original file name and the mapping name, and convert it back when the user downloads. pre;"> </span>//Mapping name<span style="white-space: pre;"> </span>String id=UUID.randomUUID().toString().replace("-", "" ); <span style="white-space: pre;"> </span>//File name<span style="white-space: pre;"> </span>String lastname=name.substring(name.lastIndexOf (".")); <span style="white-space: pre;"> </span>//The name file formats are all found---combination<span style="white-space: pre;"> < /span>String filename =id+lastname; <span style="white-space: pre;"> </span>//Copy stream. Let it write to the corresponding location <span style="white-space: pre;"> </span>FileUtils.copyInputStreamToFile(it.getInputStream(), new File(path+"/"+filename));}<span style = "white-space: pre;"> </span>}} catch (FileUploadException e) { <span style="white-space: pre;"> </span>throw new RuntimeException("File upload parsing error. "+ e); <span style="white-space: pre;"> </span>} finally{ <span style="white-space: pre;"> </span>if(it0==null){ <span style="white-space: pre;"> </span>it0.delete();//Delete temporary file<span style="white-space: pre;"> </span>}}out.close() ;}}</span><span style="font-size: 18px;"> </span> File download source code: [html] view plaincopyprint?<span style="font-size:14px;">package cn .hncu.downImg; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java. io.PrintWriter; import java.net.URLEncoder; import javax. servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRe sponse; public class DownImgDemo extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletExcepti on, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOExcep tion { //Set the corresponding header response.setContentType("application/force-download"); //Send the user name to the front desk /*Transfer the fixed username String aa="1.jpg";//If it is in Chinese, you need to encode aa=URLEncoder.encode(aa, "UTF-8"); response.setHeader("Content-Disposition", "attachment ;filename='"+aa+"'");///// You must add "attachment;", otherwise it will become a browsing*/ OutputStream out=response.getOutputStream();//Get the output stream String name=request . getParameter("name");//The parameter name passed from the client service is int num=name.lastIndexOf("/"); String aa=name.substring(num+1); aa=URLEncoder.encode(aa, " UTF-8");//If it is required to recode in Chinese//System.out.println(aa); response.setHeader("Content-Disposition","attachment;filename='"+aa+"'");// Get the file name passed from there so that it can be downloaded when storing String filename=this.getServletContext().getRealPath(name);//Get the absolute path InputStream in=new FileInputStream(filename); b yte[] b=new byte[1024]; int len=0; while((len=in.read(b))!=-1){ out.write(b, 0, len);}}}</span>< span style="font-size: 18px;"> </span>The above is all about this article, I hope it will be helpful to everyone's learning.