javaweb上传与下载
今天了解了一下javaweb的上传与下载的简单功能的实现。通过这个小demo可以实现将本地的文件下载至sever服务器的指定文件夹中。以及将项目文件夹里的指定文件下载至本计算机中。具体界面如下图所示,点击提交可以上传图片,点击图片这个超链接可实现图片的下载
具体代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-如果上传文件表单的提交方式必须为post,且form中必须有enctype="multipart/form-data" ->
<form action="UploadServlet" method="post" enctype="multipart/form-data">
学号:<input type="text" name="sno"/><br/>
姓名:<input type="text" name="sno"/><br/>
上传照片:<input type="file" name="spicture"/><br/>
<input type="submit" value="提交"/>
</form>
<a href="DownloadServlet?filename=图片.png">图片</a>
</body>
</html>
index.jsp
package studentServlet;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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#HttpServlet()
*/
public DownloadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取需要下载的文件名
String fileName = request.getParameter("filename");//form ,a href ,servlet?a=b
//下载文件徐设置消息头
response.addHeader("content-Type", "aspplication/octet/stream");//MIME类型:二进制类型的(所有的内容都可以下载)
response.addHeader("content-Disposition", "attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
//Servlet通过文件的地址将文件转为输入流读到Servlet中
InputStream in = getServletContext().getResourceAsStream("/res/图片.png");
//通过输出流,将刚刚已转为输入流的文件输出给用户
ServletOutputStream out = response.getOutputStream();
byte[] bs = new byte[10];
int len=-1;
while((len=in.read(bs))!=-1) {
out.write(bs,0,len);
}
out.close();
in.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);
}
}
DownloadServlet
package studentServlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadBase;
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#HttpServlet()
*/
public UploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");//设置请求编码
response.setCharacterEncoding("utf-8");//设置响应编码
response.setContentType("text/html; charset=UTF-8");//设置响应界面编码
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
try {
if(isMultiPart) {//判断前台form是否有enctype="multipart/form-data"字段
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String temppath = request.getSession().getServletContext().getRealPath("loadtemp");
factory.setSizeThreshold(20480);//设置临时缓冲区文件大小
factory.setRepository(new File(temppath));
//控制单个文件的大小
upload.setSizeMax(40960);//字节B
//通过ParseRequest解析form中的所有请求字段,并保存到items集合当中
List<FileItem> items = upload.parseRequest(request);
//遍历items中的数据
Iterator<FileItem> iter = items.iterator();
while(iter.hasNext()) {
FileItem item = iter.next();
String itemName = item.getFieldName();
int sno = -1;
String sname = null;
if(item.isFormField()) {//判断前台字段是普通form表单字段还是文件字段
if(itemName.equals("sno")) {
sno = Integer.parseInt(item.getString("UTF-8"));
}else if(itemName.equals("sname")) {
sname = item.getString("UTF-8");
}else {
System.out.println("其他字段。。。");
}
}else {
//文件上传
//文件名getFieldName是获取普通表单字段的name的值
//getName()是获取文件名
String fileName = item.getName();
String ext = fileName.substring(fileName.indexOf(".")+1);
if(!(ext.equals("png")||ext.equals("jpg")||ext.equals("gif"))) {
System.out.println("照片格式有误,只能是png,jpg,gif格式");
return;
}
//获取文件内容并上传
//定义文件路径:指定上传位置
//获取服务器路径:
String path = request.getSession().getServletContext().getRealPath("load");
File file = new File(path,fileName);
item.write(file);
System.out.println("上传成功!!!");
return;
}
}
}
}catch (FileUploadBase.SizeLimitExceededException e) {
System.out.println("文件超出最大传输范围,不能超过40kb");
}
catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception 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);
}
}
UploadServlet
其中index.jsp是页面的代码,DownloadServlet是下载的servlet代码,UploadServlet是上传的代码。
今天的学习就到这里,明天打算学习一下javaweb的EL以及jstl。