跟随小破站学习java web第十五天_小破站的学习陪伴-程序员宅基地

技术标签: servlet  乱码  java web  

file_upload.jsp

<%@ 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>Insert title here</title>
</head>
<body>
	<h1>文件上传</h1>
	<form action="FileUploadDemo" method="post" enctype="multipart/form-data">
		姓名:<input type="text" name="uname"><br>
		上传文件:<input type="file" name="fileupload"><br>
		<input type="submit" value="上传朋友圈">
		
	</form>
</body>
</html>
public class FileUploadDemo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * 准备:导入两个jar包&页面3处
		 	1. 创建工厂类
		 	2. 创建解析器ServletFileUpload
		 	3. 使用ServletFileUpload中的List<FileItem> parseRequest(request)
		 	4. FileItem中的write()方法,写到服务器。
		 */
		//1. 创建工厂类
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//2. 创建解析器ServletFileUpload
		ServletFileUpload upload = new ServletFileUpload(factory);
		//获取upload的真实路径
		String realPath = this.getServletContext().getRealPath("/upload");
		System.out.println(realPath);
		//3. 使用ServletFileUpload中的List<FileItem> parseRequest(request)
		try {
			List<FileItem> list = upload.parseRequest(request);
			//迭代集合,查找指定的文件
			for (FileItem fileItem : list) {
				if(fileItem.isFormField() == false){
					String filePath = realPath+"/"+fileItem.getName();
					File file = new File(filePath); 
					//4. FileItem中的write()方法,写到服务器
					fileItem.write(file);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.getWriter().write("upload success!");
		
		//获取参数
//		String username = request.getParameter("uname");
//		String fileupload = request.getParameter("fileupload");
//		
//		System.out.println(username);
//		System.out.println(fileupload);
	}

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

}

注意:此时会将文件复制到当前项目所在服务器目录下/upload目录下!

优化上传问题

public class FileUploadDemo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		
		//1. 创建工厂类
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//2. 创建解析器ServletFileUpload
		ServletFileUpload upload = new ServletFileUpload(factory);
		//获取upload的真实路径
		String realPath = this.getServletContext().getRealPath("/upload");
//		System.out.println(realPath);
		//设置单个文件的上传大小
		upload.setFileSizeMax(2*1024);
		//3. 使用ServletFileUpload中的List<FileItem> parseRequest(request)
		try {
			List<FileItem> list = upload.parseRequest(request);
			//迭代集合,查找指定的文件
			for (FileItem fileItem : list) {
				if(fileItem.isFormField() == false){
					String uuid = UUID.randomUUID().toString().replace("-", "");
					String filePath = realPath+"/"+uuid+fileItem.getName();
					File file = new File(filePath); 
					//4. FileItem中的write()方法,写到服务器
					fileItem.write(file);
				}
			}
		}catch (FileSizeLimitExceededException e) {
			writer.write("单个文件大小不能超过2k");
			e.printStackTrace();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

file_download.jsp

<%@ 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>Insert title here</title>
</head>
<body>
	<h1>宝库</h1>
	<a href="${pageContext.request.contextPath }/FileDownLoadDemo?fileName=music.mp3">music.mp3</a>
	<a href="${pageContext.request.contextPath }/FileDownLoadDemo?fileName=picture.jpg">picture.jpg</a>
	<a href="${pageContext.request.contextPath }/FileDownLoadDemo?fileName=china.txt">china.txt</a>
	<a href="${pageContext.request.contextPath }/FileDownLoadDemo?fileName=邓紫棋.mp4">邓紫棋.mp4</a>
</body>
</html>
public class FileDownLoadDemo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
//		response.setContentType("text/html;charset=UTF-8");
		
		//获取文件名
		String fileName = request.getParameter("fileName");
		//通过fileName获取该文件的真实路径
		String realPath = this.getServletContext().getRealPath("/WEB-INF/download");
		String downloadPth = realPath+"/"+fileName;
		System.out.println(downloadPth);
		
		//设置浏览器响应体文件类型
		String mimeType = request.getServletContext().getMimeType(fileName);
		response.setContentType(mimeType);
		//解决文件名中文乱码问题
		String header = request.getHeader("User-Agent");
		if(header != null && header.contains("Firefox")) {
			fileName = "=?utf-8?B?"+new BASE64Encoder().encode(fileName.getBytes("utf-8"))+"?=";
		}else {
			fileName = URLEncoder.encode(fileName, "UTF-8");
		}
		//设置浏览器响应体内容格式,为附件格式。(告诉浏览器别播放,下载)
		response.setHeader("Content-Disposition", "attachment; filename="+fileName);
		
		//读取目标资源,同时写到客户端(下载)
		//创建读入流
		FileInputStream fis = new FileInputStream(downloadPth);
		//创建写出流
		ServletOutputStream ops = response.getOutputStream();
		byte[] b = new byte[1024];
		while(fis.read(b) != -1){
			ops.write(b);
		}
		
		ops.close();
		fis.close();
	}

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

}

注意:当在servlet中设置setContextType(“text/html;charset=UTF-8”)时,只能读取txt文件,需要设置浏览器响应文件类型、解决中文乱码问题、设置浏览器响应格式!

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Mars_LJ/article/details/108224273

智能推荐

TortoiseGit解决冲突-程序员宅基地

文章浏览阅读1w次,点赞12次,收藏52次。TortoiseGit解决冲突问题概述场景重现解决冲突问题概述在项目实施过程中,多人维护同一份文件或代码时经常会在本地Commit完再从远程仓库Pull时出现冲突。这时需要保留自己的内容,同时也保留远程仓库原来的数据信息。场景重现新建test仓库,仓库中新建文本文档,在其中输入内容123。在PC上两个不同的地方分别克隆test仓库,以此来模拟两个不同的维护人员。接下来模拟冲突产生过程:在test1文件夹中的文档中新增内容“1111111”,右击->Commit,之后右击->_tortoisegit解决冲突

Notepad++设置文件默认语言和关键字高亮显示_notepad语言abaqus关键词-程序员宅基地

文章浏览阅读9.4k次,点赞4次,收藏8次。1、【设置】–>【语言格式设置】2、左侧【语言】框中选择文本语言(此处以SQL为例)3、在【自定义扩展名】中添加文件格式(多个格式之间用空格分隔)此处添加的两种文件格式为hql和txt,保存之后,下次使用Notepad++打开.sql .hql .txt文件时将默认使用SQL语言,同理可按需求设置其他文件格式4、自定义高亮显示关键字(多个关键字用空格分隔)在Notep..._notepad语言abaqus关键词

微信小程序_js 延时 微信小程序-程序员宅基地

文章浏览阅读264次。微信小程序 一般组件的方法只能通过点击事件触发 如果想要它自己调取可以通过下面的方法ready(){//自带的方法 ready 返回一个结果 this.getbanner() }..._js 延时 微信小程序

Lunix设置RSA秘钥登录_ssh 指定 id_rsa-程序员宅基地

文章浏览阅读1.3k次。Lunix设置RSA秘钥登录_ssh 指定 id_rsa

FreeNas OS Windows SMB 所有用户登录后共享同一文件夹_freenas 多用户 多文件夹-程序员宅基地

文章浏览阅读1.4k次。@ [TOC]** FREENAS WINDOWS SMB 登录后公共使用文件夹的共享设置。。**FreeNas OS Windows SMB 所有用户登录后共享同一文件夹。。有时候即使是公用文件夹,也不想给没有认证的使用者看到。上期讲了,不登录系统才能使用的共享文件夹,今天讲一下,要登录系统后才能看到及使用的公共文件夹内的文件。设置起来比较复杂。..._freenas 多用户 多文件夹

面试题目--预处理与宏_用宏名代替字符串时,只做简单的代换,不进行任何计算,也不进行正确性检查-程序员宅基地

文章浏览阅读155次。1、预处理--条件编译#ifdef 宏名 程序段1#else 程序段2#endif#include &lt;iostream&gt;using namespace std;#define DEBUGint main(){#ifdef DEBUG printf("We have defined DEBUG!");#else p..._用宏名代替字符串时,只做简单的代换,不进行任何计算,也不进行正确性检查

随便推点

C/C++基础知识总结——数据的共享与保护-程序员宅基地

文章浏览阅读109次。1. 标识符的作用域与可见性  1.1 作用域    标识符的作用域包括:函数原型作用域、局部作用域、类作用域、命名空间作用域  (1) 函数原型作用域:函数的参与的作用域就是从函数的开始到结束  (2) 局部作用域:void fun(int a){ int b = a; cin>>b; if(b>0) ..._c++数据的共享和保护实验总结

无法解析的外部符号 _cublascreate_v2@4,等一系列的类似问题(用于x64位。)以及vs2013+cuda8.0+win10配置过程_cuda程序报错无法解析的外部符号cublascreate_v2,该函数在main函数中被引用-程序员宅基地

文章浏览阅读9.4k次,点赞13次,收藏35次。首先贴出我的问题,解决的就是这个问题。要解决这个问题,首先要看你的cuda环境配置的是否正确,那么就要从头跟着我们走一遍,再检查一下您配置的是否正确。1&gt;1.cu.obj : error LNK2019: 无法解析的外部符号 cublasDestroy_v2,该符号在函数 main 中被引用1&gt;1.cu.obj : error LNK2019: 无法解析的外部符号 cudaFree,该..._cuda程序报错无法解析的外部符号cublascreate_v2,该函数在main函数中被引用

appium+python开发09--框架封装,作用yaml作数据驱动_from appium.webdriver.webdriver import webdriver用法-程序员宅基地

文章浏览阅读1.3k次。雪球APP:实现股票查询:(Search)股票选择:(Selected)登陆操作的封装:Profilepage页面登陆页面目录结构:AndroidClient.py主要实现app的安装的启动功能:from appium import webdriverfrom appium.webdriver.webdriver i..._from appium.webdriver.webdriver import webdriver用法

spring集成kafka运行时报错:Failed to construct kafka producer] with root cause-程序员宅基地

文章浏览阅读5.2k次。spring集成kafka运行时报错:Failed to construct kafka producer] with root causeorg.apache.kafka.common.KafkaException: class org.apache.kafka.common.serialization.StringDeserializer is not an instance of org.apache.kafka.common.serialization.Serializer如图:_failed to construct kafka producer

C++多线程启动、暂停、继续与停止_c++线程启动与挂起-程序员宅基地

文章浏览阅读8.7k次,点赞11次,收藏65次。在自动化设备中,设备在运转过程中,为了防止设备伤人,通常会在设备门入口安装光幕,当光幕被遮挡时,设备必须暂停,确保安全的情况下,按下继续按钮,设备继续运转。对于多工位的设备,每个工位可能交由一个线程处理,因此暂停时,需要令这些线程暂时挂起。C++11标准以后,加入了线程相关的接口,在应用中经常需要使线程暂停,在windows API中可以使用suspend 使线程挂起,但容易产生一些意想不到的问题,官方并不推荐使用。但 C++11 中没有使线程暂停的接口。现用条件变量与互斥锁封装一个线程类,实现线程的暂._c++线程启动与挂起

win10 计算器提示:需要新应用打开此calculator_ms-calculator-程序员宅基地

文章浏览阅读3.8w次,点赞9次,收藏9次。升级win10后,在“开始“下方搜索不到计算器,运行calc,会出现需要新应用打开此Calculator,打开应用商店,找到计算器,仍然可以被使用,我怀疑是我自己在清理PC的注册表的时候将系统的一些设置修改了,导致c:\Windows\System32\calc这个程序与应用商店里面的计算器之间的对应关系没有了,这样每次运行calc的时候就会出现这种问题。下面是我的解决办法:以管理员身份运行Win..._ms-calculator

推荐文章

热门文章

相关标签