Upload and download files in Java Web development

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/suoyue_py/article/details/98759490

How to upload files

Web development in two steps to achieve file upload function:

  • Upload page to add entries in the Web
  • Read data uploaded file in Servlet and save to your local hard drive

Since most of the files are uploaded through a form submitted to the server in the form, so you need to create a form for submitting a page to upload files.
Upload Files page of the form to be configured as follows:

  1. First of all to create a form for submitting a page to upload files
  2. In the page, you need to use <input type = "file"> tag to add file upload entries in the Web page
  3. You must set the input entry of the name attribute, otherwise the browser will not send data upload file
  4. Must be a form page method attribute is set to post embodiment, the enctype attribute is set to "multipart / form-data" type.
    Sample code:
    <%--指定表单的enctype属性以及提交方式--%>
    <form enctype="multipart/form-data" method="post">
    	<%--指定标记的类型和文件域的名称--%>
    	选择上传文件:< inpurt type="file" name="myfile"/><br />
    </form>

Providing a tissue source components Apache Commons-the FileUpload , can easily be "multipart / form-data" parsed request various types of form fields, and to upload one or more files, but can also limit the size of the file upload and so on. Need to import use commons-fileupload.jar and commons-io.jar two JAR package, Quguan network: "http://commons.apache.org/" download (in the Components column URL page Apache Commons Proper below the table the FileUpload and IO).

How to download files

Download achieved without the use of third-party components, directly Servlet class and an input / output streams can.
And access to server files is different, download the files you want to achieve, not only need to specify the path to the file, but also need to set up two response headers in HTTP protocol:

//设置接受程序处理方式
Content-Disposition:attachment;filename=
//设定实体内容的MIME类型(多用途互联网邮件扩展类型)
Content-Type:appliccation/x-msdownload

Description of the downloaded file realization of the principle:
first get the address to download the file and creates the file input stream of bytes, and then read the contents of the file downloaded by the stream according to the address, and finally read the contents of the output stream into the target file .

Examples of a question:

Please upload a file UploadServlet implementation class in accordance with the following requirements of the design?
Requirements are as follows:
1) the known form document form.html form defines a named file name text box and the domain name of myfile includes prerequisite file upload.
2) In the doPost () method, the file upload write relevant code.
3) upload files saved in the current file upload application's folder.
Solution: UploadServlet code is as follows:

public class UploadServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		try {			// 创建工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setRepository(new File("e:\\Target"));
			ServletFileUpload fileupload = new ServletFileUpload(factory);			// 创建 fileupload 组件
			fileupload.setHeaderEncoding("utf-8");
			List<FileItem> fileitems = fileupload.parseRequest(request);			// 解析 request
			PrintWriter writer = response.getWriter();
			for (FileItem fileitem : fileitems) {			// 遍历集合
				if (fileitem.isFormField()) {				// 判断是否为普通字段
					String name = fileitem.getFieldName();					// 获得字段名和字段值
					String value = fileitem.getString("utf-8");
				} else {					// 上传的文件路径
					String filename = fileitem.getName();
					writer.print("文件来源:" + filename + "<br>");
					filename = filename					// 截取出文件名
							.substring(filename.lastIndexOf("\\") + 1);
					writer.print("成功上传的文件:" + filename + "<br>");
					filename = UUID.randomUUID().toString() + "_" + filename;				// 文件名需要唯一
					String webPath = "/upload/" + filename;					// 在服务器创建同名文件
					String path = getServletContext().getRealPath(webPath);
					File file = new File(path);					// 创建文件
					file.getParentFile().mkdirs();
					file.createNewFile();
					InputStream in = fileitem.getInputStream();					// 获得上传文件流
					OutputStream out = new FileOutputStream(file);			// 获得写入文件流
					byte[] buffer = new byte[1024];					// 流的对拷
					int len;
					while ((len = in.read(buffer)) > 0)
						out.write(buffer, 0, len);
					in.close();					// 关流
					out.close();
					fileitem.delete();					// 删除临时文件
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

Question two examples:

Please write a file name used to implement file download programs, download files and ensure Chinese garbage problem can not appear?
Solution:
implementation steps that function as follows:
(1) create a download page download.jsp

<%@ page language="java" import="java.util.*" 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>文件下载</title>
</head>
<body>
<a href="${pagContext.request.contextPath}/chapter06/DownloadServlet"}>
		文件下载
	</a>
	<br />
</body>
</html>

(2) preparation of DownloadServlet class that is primarily used to set the file to be downloaded, and the file is opened in the browser mode, and use the encode (String s, String enc) method, the URL encoded string in the form of a specified output, to prevent the emergence of Chinese file name garbled

import java.io.*;
import java.net.URLEncoder;
import javax.servlet.*;
import javax.servlet.http.*;
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
         response.setContentType("text/html;charset=utf-8");
          // 获得绝对路径创建文件对象
         String path=getServletContext().getRealPath("/download/人物.jpg");
         File file=new File(path);
          // 通知浏览器以下载的方式打开文件
		response.addHeader("Content-Type", "application/octet-stream");
         response.addHeader("Content-Disposition","attachment;filename="
         +URLEncoder.encode(file.getName(),"utf-8"));
		InputStream in=new FileInputStream(file);         // 通过文件对象获取文件相关的输入流
		OutputStream out = response.getOutputStream();         // 获取response对象的输出流
         byte [] buffer=new byte[1024];
		int len;
		while((len=in.read(buffer))!=-1){
			out.write(buffer,0,len);
		}
	}
	public void doPost(HttpServletRequest req, HttpServletResponse  resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}

(3) use IE browser to visit the download.jsp, click the page in the file download link to download the file to save

Guess you like

Origin blog.csdn.net/suoyue_py/article/details/98759490