一:简介
方法一:把文件上传到本地磁盘,但是这种方法不能将文件(例如我这里是图片)在internet上面真正地访问到,因为通过其他设备不能通过127.0.0.1的任何盘访问到在我这里的磁盘数据,所以这种方法仅仅是一种调试程序中的;
方法二:听网上说当web程序上传到linux上发布之后不存在重置,所以接下来就要说方法二;把文件上传服务器,获取文件的时候通过相对路径,虽然在调试中一因为tomcat内容重置,但是上传linux发布后就不会发生这种情况了,并且可以弥补方法一中其他用户不能通过web获得文件(图片)的弊端;
二;方法一代码:
1.要有commons-fileupload.jar和commons-io.jar
2.上传要是不处理存的盘的地方,一旦修改web里东西或重启,上传后都会以现在写的东西覆盖之前写的东西,这样之前上传的东西都会没有,所以我们要修改Eclipse里面配置apache-tomcat时出现的Servers里面的server.xml
(1).打开server.xml,找到并加入(详细内容请看:https://blog.csdn.net/qq_1017097573/article/details/52291015)
(2).```在对应的盘中新建文件夹.
3.
(1).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>
<form action="../uploadservlet"method="post"enctype="multipart/form-data">
文件名字:<input name="sname"/><br/>
上传文件: <input type="file"name="pic">
<br/>
<input type="submit"value="上传文件">
</form>
</body>
</html>
(2).servlet代码:把m.jpg储存在D盘的uoload
package uploadsth;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class 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
{
// TODO Auto-generated method stub
// request.setCharacterEncoding("utf-8");
// response.setCharacterEncoding("utf-8");
// response.setCharacterEncoding("text/html; charset=UTF-8");
//System.out.println("uploadServlet1");
//上传
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart) //判断前台有误Multipart属性
{
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List<FileItem> items = upload.parseRequest(request);
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
String sname=null;
while (iter.hasNext()) {
FileItem item = iter.next();
String itemName=item.getFieldName();
int sno=-1;
if (item.isFormField()) {
if(itemName.equals("sno"))
{
String filedValue=item.getString();//获取表单项内容
// System.out.println("sno= "+item.getString());
}
else if(itemName.equals("sname"))
{
sname= item.getString("UTF-8");
// System.out.println("sname= "+sname);
}
else {
System.out.println("其他字段");
}
}
else {
//pic 文件上传
//getname获取文件名
String longFileName = item.getName();
char indexChar = '\\';
// String filename= System.currentTimeMillis()+item.getName().substring(longFileName.lastIndexOf(indexChar) + 1,
// longFileName.length());
// System.out.println("sname= "+sname);
String filename=sname+".jpg";
// //获取文件类型
// String contentType=item.getContentType();
InputStream is=item.getInputStream();//输入流,上传文件的内容
//上传到服务器,因为有些不支持存在D,C,E盘
String datestr=null;
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
Date date=new Date();
datestr=sdf.format(date);
//String path=this.getServletContext().getRealPath("/pic")+"/"+datestr;
// String path=this.getServletContext().getRealPath("/up")+"/"+filename;
// File dirfile=new File(path);
// //若该目录不存在
// if(!dirfile.exists())
// {
// dirfile.mkdir();
// }
//String path=this.getServletContext().getRealPath("/up");
String path="D:/objimgs/upload";
//System.out.println("ok");
//创建目标文件,将来用于保存上传文件
// System.out.println("path= "+path);
// System.out.println("filename= "+filename);
File dexcFile=new File(path,filename);
//创建文件输出流
OutputStream os=new FileOutputStream(dexcFile);
//将输出流中的数据输出到输出流中
int len=-1;
byte[] buf=new byte[1024];
/*
* f(len=is.read(buf))!=-1
要运行时ead()从输入流中读取下一个字节。如果没有字节可读(也就是read()读到文件最后了)read()返回-1.
如果if=true:
就还要读取数据
则:len=is.read(b
*/
while((len=is.read(buf))!=-1)
{
os.write(buf,0,len);
}
os.close();
is.close();
request.getRequestDispatcher("./upload/upload_show.jsp").forward(request,response);
}
}
}
else {
throw new RuntimeException("当前不是multipart请求");
}
}
catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
// ServletInputStream is=request.getInputStream();
// byte[] buf=new byte[1024];
// PrintWriter out=response.getWriter();
// int len=-1;
//
// while((len=is.read(buf))!=-1)
// {
// String str=new String(buf,0,len);
// out.print(str);
// }
}
//
// /**
// * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
// */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//System.out.println("post");
doGet(request, response);
}
}
4.上传的的图片(m.jpg)显示在页面上
<%@page import="org.eclipse.jdt.internal.compiler.ast.ThisReference"%>
<%@ 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>
<% String path="http://localhost:8888/objimgs"+"/m.jpg";
//String path="./up/m.jpg";
%>
<img src="<%=path %>"alt="go"/>
</body>
</html>
ps:以上代码的强调:
方法二代码:
1.在编译器中在这个web项目webapp中添加一个up文件夹–>用来作为上传文件的地址(也可以在tomcat下的wtpwebapps中找到这个web项目,在这个项目下新建一个up文件夹,用来储存上传文件的地址,但是随着在编译器中的文件的重新编译,新建的up文件夹以及它的下级文件会消失);
2.jsp1不变(文件上传页面不变):
<%@ 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>
<form action="../uploadservlet"method="post"enctype="multipart/form-data">
文件名字:<input name="sname"/><br/>
上传文件: <input type="file"name="pic">
<br/>
<input type="submit"value="上传文件">
</form>
</body>
</html>
3.servlet:后端将前端传来的图片文件(这里设置m.jpg,m是文件名字,前端设置的)
package uploadsth;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class 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
{
// TODO Auto-generated method stub
// request.setCharacterEncoding("utf-8");
// response.setCharacterEncoding("utf-8");
// response.setCharacterEncoding("text/html; charset=UTF-8");
//System.out.println("uploadServlet1");
//上传
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart) //判断前台有误Multipart属性
{
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List<FileItem> items = upload.parseRequest(request);
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
String sname=null;
while (iter.hasNext()) {
FileItem item = iter.next();
String itemName=item.getFieldName();
int sno=-1;
if (item.isFormField()) {
if(itemName.equals("sno"))
{
String filedValue=item.getString();//获取表单项内容
// System.out.println("sno= "+item.getString());
}
else if(itemName.equals("sname"))
{
sname= item.getString("UTF-8");
// System.out.println("sname= "+sname);
}
else {
System.out.println("其他字段");
}
}
else {
//pic 文件上传
//getname获取文件名
String longFileName = item.getName();
char indexChar = '\\';
// String filename= System.currentTimeMillis()+item.getName().substring(longFileName.lastIndexOf(indexChar) + 1,
// longFileName.length());
// System.out.println("sname= "+sname);
String filename=sname+".jpg";
// //获取文件类型
// String contentType=item.getContentType();
InputStream is=item.getInputStream();//输入流,上传文件的内容
//上传到服务器,因为有些不支持存在D,C,E盘
String datestr=null;
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
Date date=new Date();
datestr=sdf.format(date);
//String path=this.getServletContext().getRealPath("/pic")+"/"+datestr;
// String path=this.getServletContext().getRealPath("/up")+"/"+filename;
// File dirfile=new File(path);
// //若该目录不存在
// if(!dirfile.exists())
// {
// dirfile.mkdir();
// }
String path=this.getServletContext().getRealPath("/up");
// String path="D:/objimgs/upload";
//System.out.println("ok");
//创建目标文件,将来用于保存上传文件
// System.out.println("path= "+path);
// System.out.println("filename= "+filename);
File dexcFile=new File(path,filename);
//创建文件输出流
OutputStream os=new FileOutputStream(dexcFile);
//将输出流中的数据输出到输出流中
int len=-1;
byte[] buf=new byte[1024];
/*
* f(len=is.read(buf))!=-1
要运行时ead()从输入流中读取下一个字节。如果没有字节可读(也就是read()读到文件最后了)read()返回-1.
如果if=true:
就还要读取数据
则:len=is.read(b
*/
while((len=is.read(buf))!=-1)
{
os.write(buf,0,len);
}
os.close();
is.close();
request.getRequestDispatcher("./upload/upload_show.jsp").forward(request,response);
}
}
}
else {
throw new RuntimeException("当前不是multipart请求");
}
}
catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
// ServletInputStream is=request.getInputStream();
// byte[] buf=new byte[1024];
// PrintWriter out=response.getWriter();
// int len=-1;
//
// while((len=is.read(buf))!=-1)
// {
// String str=new String(buf,0,len);
// out.print(str);
// }
}
//
// /**
// * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
// */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//System.out.println("post");
doGet(request, response);
}
}
4.获得上传图片的jsp界面(获取上传的m.jpg文件)
<%@page import="org.eclipse.jdt.internal.compiler.ast.ThisReference"%>
<%@ 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>
<%// String path="http://localhost:8888/objimgs"+"/m.jpg";
String path="./up/m.jpg";
%>
嘻嘻
<img src="<%=path %>"alt="go"/>
</body>
</html>