Fifteenth day of javaweb learning

File Upload and Download

File Upload
To achieve the upload function of Web development, there are usually two steps to complete: one is to add the upload entry to the Web page; The second is to read the data of the uploaded file in Servlet and save it to the local hard disk.

Uploads are mostly submitted to the server as forms, using tags.

There are two things to note when using labels:

1. The name property must be set or the browser will not send data for the uploaded file.

2. The method property must be set to post and the ectype property to the "multipart/form-data" type.

Because reading the uploaded data directly from Servlet and parsing the corresponding file data is a very cumbersome task. To facilitate the processing of uploaded data, the Apache organization provides an open source component, Commons-FileUpload. This component can parse out various form fields requested by the "multipart/form-data" type, and upload one or more files, as well as limit the size of the uploaded files, etc. It has excellent performance and is extremely simple to use.

For file upload, the browser submits the file as a stream to the server during the upload process. If it is more troublesome to get the input stream of the uploaded file directly using Servlet and then parse the request parameters inside, the open source tool common-fileupload which uses Apache is generally chosen as the file upload component. The jar package of this common-fileupload upload component can be downloaded on apache's official website or found under the lib folder of struts, which is the basis for struts upload. The common-fileupload relies on the common-io package, so it needs to be downloaded.
  
Development Environment Setup
Create a chapter12 project that incorporates Apache's commons-fileupload file upload component's associated Jar package

Implement file upload

Create Upload Page
Create a form.jsp's j page, which provides a form form for file upload

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                            "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload</title>
</head>
<body>
 	<form action="UploadServlet" method="post"   enctype="multipart/form-data">
 		<table width="600px">
 			<tr>
 				<td>Uploader</td>
 				<td><input type="text" name="username" /></td>
 			</tr>
 			<tr>
 				<td>Upload Files</td>
 				<td><input type="file" name="myfile" /></td>
 			</tr>
 			<tr>
 				<td colspan="2"><input type="submit" value="upload" /></td>
 			</tr>
 		</table>
 	</form>
</body>
</html>

Create Servlet
Write a class for the UploadServlet that is primarily used to get information about forms and their uploaded files

package cn.itcast.fileupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		    
		try {
			
			response.setContentType("text/html;charset=utf-8");
			
			DiskFileItemFactory factory=new DiskFileItemFactory();
			
			File f=new File("d:\\Temp");
			if(!f.exists()) {
				f.mkdirs();
			}
			
			factory.setRepository(f);
			factory.setSizeThreshold(1024*1024);
			
			ServletFileUpload fileupload=new ServletFileUpload(factory);
			fileupload.setHeaderEncoding("utf-8");
			List<FileItem> fileitems=fileupload.parseRequest(request);
			
			for(FileItem fileitem:fileitems) {
				boolean flag=fileitem.isFormField();
				if(flag) {
					
					String name=fileitem.getFieldName();
					if(name.equals("username")) {
						if(!fileitem.getString().equals("")) {
							
							String value=fileitem.getString("utf-8");
							
							response.getWriter().print("Uploader:"+value+"<br/>");
						}
					}
				}else {
					String filename=fileitem.getName();
					if(filename!=null&& !filename.equals("")) {
						
						response.getWriter().print("Uploaded file name:"+filename+"<br/>");
						filename=filename.substring(filename.lastIndexOf("\\")+1);
						
						filename=UUID.randomUUID().toString()+"_"+filename;
						
						String webPath="/upload2005/";
						
						String filepath=getServletContext().getRealPath(webPath+filename);
						
						File file=new File(filepath);
						file.getParentFile().mkdirs();
						file.createNewFile();
						
						InputStream in=fileitem.getInputStream();
						FileOutputStream out=new FileOutputStream(file);
						
						byte[] buffer=new byte[1024];
						int len=0;
						while((len=in.read(buffer))>0) {
							out.write(buffer,0,len);
						}
						
						in.close();
						out.close();
						
						fileitem.delete();
						response.getWriter().print("File uploaded successfully"+"<br/>");
						
					}
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Start the project and view the results


File Download
Create download page. JSP This page has a link written for download

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@page import="java.net.URLEncoder"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                            "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Download</title>
</head>
<body>
<a href="/chapter12/DownloadServlet?filename=Chongqing.jpg">File Download</a>

</body>
</html>

Create Servlet
Create the DownloadServlet class, which is used to set the download to be downloaded and how the file opens in the browser

package cn.itcast.fileupload;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownloadServlet
 */
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	      
		  response.setContentType("text/html;charset=utf-8");
		  String filename=request.getParameter("filename");
		  filename=new String (filename.getBytes("iso-8859-1"),"utf-8");
		  
		  String fileType=getServletContext().getMimeType(filename);
		  
		  response.addHeader("Content-Type", fileType);
		  response.addHeader("Content-Disposition", "attachment;filename");
		  
		  String folder="/download/";
		  
		  InputStream in=getServletContext().getResourceAsStream(folder+filename);
		  OutputStream out=response.getOutputStream();
		  
		  byte[] buffer=new byte[1024];
		  int len=0;
		  while((len=in.read(buffer))>0) {
			  out.write(buffer,0,len);
		  }
		  
		  in.close();
		  out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Create download directory and files
Create a folder named download under the WebContent directory of the project and place a Chongqing in the file. jpg file.

Start the project and view the results

Keywords: Java

Added by gooney0 on Sat, 08 Jan 2022 19:39:05 +0200