servlet文件上传下载
㈠ java中Servlet上传文件到服务器指定目录,报路径不存在的错误,我QQ,394576483
可以在程序中判断一下该目录是否存在,如果不闹悔存在,创建目录。
Filef=newFile("D:\apache-tomcat-6.0.20\webapps\up1\WEB-INFO\files");
if(!f.exists()){
f.mkdirs();
}
另外搜液,你这个路径不太好,如果你的war包部署在tomcat上,是没有解开成一个世弯物目录,那文件上传肯定会失败。建议你换一个实际存在的目录,用来存放文件。
㈡ 怎样使用javaweb实现上传视频和下载功能
文件上传就是将客户端资源,通过网路传递到服务器端。
因为文件数据比较大,必须通过文件上传才可以完成将数据保存到数据库端的操作。
文件上传的本质就是IO流操作。
演示:文件上传应该如何操作?
浏览器端:
1.method=post 只有post才可以携带大数据
2.必须使用<input type='file' name='f'>要有name属性
3.encType="multipart/form-data"
服务器端:
request对象是用于获取请求信息。
它有一个方法 getInputStream(); 可以获取一个字节输入流,通过这个流,可以读取到
所有的请求正文信息.
文件上传原理:
浏览器端注意上述三件事,在服务器端通过流将数据读取到,在对数据进行解析.
将上传文件内容得到,保存在服务器端,就完成了文件上传。
注意:在实际开发中,不需要我们进行数据解析,完成文件上传。因为我们会使用文件上传的工具,它们已经封装好的,提供API,只要调用它们的API就可以完成文件上传操作.我们使用的commons-fileupload,它是apache提供的一套开源免费的文件上传工具。
代码演示文件上传的原理:
在WebRoot下新建upload1.jsp
[html]view plain
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>MyJSP'index.jsp'startingpage</title>
</head>
<body>
<!--encType默认是application/x-www-form-urlencoded-->
<formaction="${pageContext.request.contextPath}/upload1"
method="POST"enctype="multipart/form-data">
<inputtype="text"name="content"><br>
<inputtype="file"name="f"><br><inputtype="submit"
value="上传">
</form>
</body>
</html>
packagecn.itcast.web.servlet;
importjava.io.IOException;
importjava.io.InputStream;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
//System.out.println("upload1servlet......");
//通过request获取一个字节输入流,将所有的请求正文信息读取到,打印到控制台
InputStreamis=request.getInputStream();
byte[]b=newbyte[1024];
intlen=-1;
while((len=is.read(b))!=-1){
System.out.println(newString(b,0,len));
}
is.close();
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doGet(request,response);
}
}
在web页面中添加上传输入项。
在Servlet中读取上传文件的数据,并保存在服务器硬盘中。
1、必须设置input输入项的name属性,否则浏览器将不会发送上传文件的数据。
2、必须把form的encType属性设为multipart/form-data 设置该值后,浏览器在上传文件时,并把文件数据附带在http请求消息体内,并使用MIME协议对上传的文件进行描述,以方便接收方对上传数据进行解析和处理。
3、表单的提交方式要设置为post。
Request对象提供了一个getInputStream方法,通过这个方法可以读取到客户端提交过来的数据。但由于用户可能会同时上传多个文件,在servlet端编程直接读取上传数据,并分别解析出相应的文件数据是一项非常麻烦的工作,示例。
为方便用户处理文件上传数据,Apache 开源组织提供了一个用来处理表单文件上传的一个开源组件( Commons-fileupload ),该组件性能优异,并且其API使用极其简单,可以让开发人员轻松实现web文件上传功能,因此在web开发中实现文件上传功能,通常使用Commons-fileupload组件实现。
使用Commons-fileupload组件实现文件上传,需要导入该组件相应支撑jar包:Commons-fileupload和commons-io。commo-io不属于文件上传组件的开发jar文件,但Commons-fileupload组件从1.1版本开始,它工作时需要commons-io包的支持。
新建Upload1Servlet 路径:/upload1
[java]view plain
在浏览器端访问信息如下:
文件上传概述
实现web开发中的文件上传功能,需要完成如下二步操作:
如何在web页面中添加上传输入项?
<input type="file">标签用于在web页面中添加文件上传输入项,设置文件上传输入项时注意:
如何在Servlet中读取文件上传数据,并保存到本地硬盘中?
㈢ ServletFileUpload.isMultipartContent(request)作用
作用有两个:
1、用于检测是否一个文件上传的请求。在fileupload包实现上传项目前,需要解析一个http请求,为了确保这个歼正请求的确是一个正确的上传文件,所以组件FileUpload提供了这样一个静态的方法。
2、用于判断是普通表单,还斗并是带文件上传的表单,起了辨别的作用。若返回值为true则是带文件上传的表单;返回值为false则是普通表单。
(3)servlet文件上传下载扩展阅读
在fileupload中, http请求中的复杂表单元素都会被看作一个FileItem对象,而且FileItem对象必须由ServletFileUpload类中的parseRequest()方法去解析HTTP请求;
再者,ServletFileUpload对象的创建需要依赖于FileItemFactory工厂而获得的上传文件FileItem对象保存至服务空改迹器硬盘,也就是指DiskFileItem对象。
㈣ jsp+servlet实现文件上传与下载源码
上传:
需要导入两个包:commons-fileupload-1.2.1.jar,commons-io-1.4.jar
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* 上传附件
* @author new
*
*/
public class UploadAnnexServlet extends HttpServlet {
private static String path = "";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/*
* post处理
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
path = this.getServletContext().getRealPath("/upload");
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload up = new ServletFileUpload(factory);
List<FileItem> ls = up.parseRequest(request);
for (FileItem fileItem : ls) {
if (fileItem.isFormField()) {
String FieldName = fileItem.getFieldName();
//getName()返回的是文件名字 普通域没有文件 返回NULL
// String Name = fileItem.getName();
String Content = fileItem.getString("gbk");
request.setAttribute(FieldName, Content);
} else {
String nm = fileItem.getName().substring(
fileItem.getName().lastIndexOf("\\") + 1);
File mkr = new File(path, nm);
if (mkr.createNewFile()) {
fileItem.write(mkr);//非常方便的方法
}
request.setAttribute("result", "上传文件成功!");
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("result", "上传失败,请查找原因,重新再试!");
}
request.getRequestDispatcher("/pages/admin/annex-manager.jsp").forward(
request, response);
}
}
下载(i/o流)无需导包:
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 下载文件
* @author
*
*/
public class DownloadFilesServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8594448765428224944L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/*
* 处理请求
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("fileName");
System.out.print("dddddddddd:" + name);
// web绝对路径
String path = request.getSession().getServletContext().getRealPath("/");
String savePath = path + "upload";
// 设置为下载application/x-download
response.setContentType("application/x-download");
// 即将下载的文件在服务器上的绝对路径
String filenamedownload = savePath + "/" + name;
// 下载文件时显示的文件保存名称
String filenamedisplay = name;
// 中文编码转换
filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="
+ filenamedisplay);
try {
java.io.OutputStream os = response.getOutputStream();
java.io.FileInputStream fis = new java.io.FileInputStream(
filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while ((i = fis.read(b)) > 0) {
os.write(b, 0, i);
}
fis.close();
os.flush();
os.close();
} catch (Exception e) {
}
}
}
㈤ 请高手给一个JS多文件上传的例子(必须兼容IE)解决追加50分。请看补充。
一、Servlet实现文件上传,需要添加第三方提供的jar包
下载地址:
1) commons-fileupload-1.2.2-bin.zip: 点击打开链接
2) commons-io-2.3-bin.zip: 点击打开链接
接着把这两个jar包放到 lib文件夹下:
二:文件上传的表单提交方式必须是POST方式,
编码类型:enctype="multipart/form-data",默认是 application/x-www-form-urlencoded
比如:
<form action="FileUpLoad"enctype="multipart/form-data"method="post">
三、举例:
1.fileupload.jsp
<%@ page language="java" import="javautil*" pageEncoding="UTF-8"%>
<%
String path = requestgetContextPath();
String basePath = requestgetScheme()+"://"+requestgetServerName()+":"+requestgetServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'fileuploadjsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="stylescss">
-->
</head>
<body>
<!-- enctype 默认是 application/x-www-form-urlencoded -->
<form action="FileUpLoad" enctype="multipart/form-data" method="post" >
用户名:<input type="text" name="usename"> <br/>
上传文件:<input type="file" name="file1"><br/>
上传文件: <input type="file" name="file2"><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
2.实际处理文件上传的 FileUpLoad.java
package comservletfileupload;
import javaioFile;
import javaio*;
import javaioIOException;
import javaioPrintWriter;
import javautilList;
import javaxservletServletException;
import javaxservlethttpHttpServlet;
import ;
import ;
import ;
import ;
import ;
import ;
/**
*
* @author Administrator
* 文件上传
* 具体步骤:
* 1)获得磁盘文件条目工厂 DiskFileItemFactory 要导包
* 2) 利用 request 获取 真实路径 ,供临时文件存储,和 最终文件存储 ,这两个存储位置可不同,也可相同
* 3)对 DiskFileItemFactory 对象设置一些 属性
* 4)高水平的API文件上传处理 ServletFileUpload upload = new ServletFileUpload(factory);
* 目的是调用 parseRequest(request)方法 获得 FileItem 集合list ,
*
* 5)在 FileItem 对象中 获取信息, 遍历, 判断 表单提交过来的信息 是否是 普通文本信息 另做处理
* 6)
* 第一种 用第三方 提供的 itemwrite( new File(path,filename) ); 直接写到磁盘上
* 第二种 手动处理
*
*/
public class FileUpLoad extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
requestsetCharacterEncoding("utf-8"); //设置编码
//获得磁盘文件条目工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//获取文件需要上传到的路径
String path = requestgetRealPath("/upload");
//如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
//设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
/**
* 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上,
* 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 tem 格式的
* 然后再将其真正写到 对应目录的硬盘上
*/
factorysetRepository(new File(path));
//设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
factorysetSizeThreshold(1024*1024) ;
//高水平的API文件上传处理
ServletFileUpload upload = new ServletFileUpload(factory);
try {
//可以上传多个文件
List<FileItem> list = (List<FileItem>)uploadparseRequest(request);
for(FileItem item : list)
{
//获取表单的属性名字
String name = itemgetFieldName();
//如果获取的 表单信息是普通的 文本 信息
if(itemisFormField())
{
//获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的
String value = itemgetString() ;
requestsetAttribute(name, value);
}
//对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
else
{
/**
* 以下三步,主要获取 上传文件的名字
*/
//获取路径名
String value = itemgetName() ;
//索引到最后一个反斜杠
int start = valuelastIndexOf("\\");
//截取 上传文件的 字符串名字,加1是 去掉反斜杠,
String filename = valuesubstring(start+1);
requestsetAttribute(name, filename);
//真正写到磁盘上
//它抛出的异常 用exception 捕捉
//itemwrite( new File(path,filename) );//第三方提供的
//手动写的
OutputStream out = new FileOutputStream(new File(path,filename));
InputStream in = itemgetInputStream() ;
int length = 0 ;
byte [] buf = new byte[1024] ;
Systemoutprintln("获取上传文件的总共的容量:"+itemgetSize());
// inread(buf) 每次读到的数据存放在 buf 数组中
while( (length = inread(buf) ) != -1)
{
//在 buf 数组中 取出数据 写到 (输出流)磁盘上
outwrite(buf, 0, length);
}
inclose();
outclose();
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
//eprintStackTrace();
}
requestgetRequestDispatcher("filedemojsp")forward(request, response);
}
}
System.out.println("获取上传文件的总共的容量:"+item.getSize());
3.filedemo.jsp
<%@ page language="java" import="javautil*" pageEncoding="UTF-8"%>
<%
String path = requestgetContextPath();
String basePath = requestgetScheme()+"://"+requestgetServerName()+":"+requestgetServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'filedemojsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="stylescss">
-->
</head>
<body>
用户名:${requestScopeusename } <br/>
文件:${requestScopefile1 }<br/>
${requestScopefile2 }<br/>
<!-- 把上传的图片显示出来 -->
<img alt="go" src="upload/<%=(String)requestgetAttribute("file1")%> " />
</body>
</html>
4结果页面:
以上就是本文的全部
㈥ servlet上传图片,目录设置问题
servlet上传图片应该保存到WEB-INF目录下的image目录核洞,理由是WEB-INF目录安全,不容易被攻击。
设置存放临时文件的目录,web根目录下的image目录写碧皮法:
实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
//设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时悔氏差存在硬盘
dfif.setSizeThreshold(4096);
dfif.setRepository(new File(request.getRealPath("/") + "image"));
㈦ dorado7 文件上传和下载功能实现 dorado7.0+struts+spring+hibenate框架 希望提供完整的代码
1. 在dorado studio的Mapping中新建一个Controller. 例如:
<controller name="file" clazz="sample.file.SampleController">
<action name="upload">
<forward name="success" path="/file/upload-success.jsp" contextRelative="false" />
<exception clazz="java.lang.Exception" path="/file/upload-failure.jsp" />
</action>
</controller>
2. 为该Controller新建一个Java实现类. 注意在新建Java类的向导中不必勾选任何待重载的父类方法.
3. 完成上述步骤后. 首先将实现类的父类改为FileController. 然后根据需要重载部分父类中的方法. 可以参考下面的例子:
1package sample.file;
2
3import java.io.File;
4import java.io.FileInputStream;
5import java.io.InputStream;
6import javax.servlet.http.HttpServletRequest;
7
8import org.apache.commons.fileupload.DiskFileUpload;
9import org.apache.commons.fileupload.FileItem;
10import com.bstek.dorado.biz.FileController;
11import com.bstek.dorado.utils.*;
12
13/**
14 * SampleController
15 */
16public class SampleController
17 extends FileController {
18 private final String WORK_DIR = "d:/temp";
19
20 /**
21 * 设定 DiskFileUpload 的相关属性.
22 * <p>关于DiskFileUpload, 你可以到www.apache.org/commons查找FileUpload的文档</p>
23 *
24 * @param request HttpServletRequest
25 * @param fileUpload DiskFileUpload
26 * @param parameters MetaData
27 */
28 protected void initFileUpload(HttpServletRequest request,
29 DiskFileUpload fileUpload, MetaData parameters) {
30 fileUpload.setSizeMax(1024 * 512); // 512K
31 }
32
33 /**
34 * 取得存放上传文件的目标目录
35 *
36 * @param request HttpServletRequest
37 * @param parameters MetaData
38 * @return String
39 */
40 protected String getUploadWorkDir(HttpServletRequest request,
41 MetaData parameters) {
42 return WORK_DIR;
43 }
44
45 /**
46 * 取得存储上传文件的文件名
47 *
48 * @param request HttpServletRequest
49 * @param fileName String
50 * @param parameters MetaData
51 * @return String
52 */
53 protected String getStoreFileName(HttpServletRequest request, String fileName,
54 MetaData parameters) {
55 return fileName;
56 }
57
58 /**
59 * 存储已经上传的文件
60 *
61 * @param request HttpServletRequest
62 * @param fileItem String
63 * @param storeFile String
64 * @param parameters MetaData
65 * @throws Exception
66 */
67 protected void storeUploadFile(HttpServletRequest request, FileItem fileItem,
68 File storeFile, MetaData parameters)
69 throws Exception {
70 super.storeUploadFile(request, fileItem, storeFile, parameters);
71
72 /** @todo 在这里您可以添加自己的代码记录上传文件信息 */
73 }
74
75 /**
76 * 取得将要下载的文件的文件名
77 *
78 * @param request HttpServletRequest
79 * @return String
80 */
81 protected String getDownLoadFileName(HttpServletRequest request) {
82 return request.getParameter("fileName");
83 }
84
85 /**
86 * 取得将要被下载的文件的文件输入流
87 *
88 * @param request HttpServletRequest
89 * @return InputStream
90 * @throws Exception
91 */
92 protected InputStream getDownloadFileInputStream(HttpServletRequest request)
93 throws Exception {
94 return new FileInputStream(WORK_DIR + File.separator +
95 request.getParameter("fileName"));
96 }
97
98}
99
4. 添加一个jsp用来上传文件. 例如:
<%@ page contentType="text/html; charset=GBK" %>
<%@ page errorPage="/dorado/exception.d" %>
<%@ taglib uri="http://www.bstek.com/dorado" prefix="d" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<center>
<form method="post" target="upload" enctype="multipart/form-data"
action="<%=request.getContextPath()%>/file.upload.d">
<input type="file" name="file1" size="40">
<br>
<input type="file" name="file2" size="40">
<br>
<input type="file" name="file3" size="40">
<hr>
<input type="submit" value=" 上传 ">
</form>
</center>
</body>
</html>
㈧ java 上传文件 问题
不用 下载相应jar包 引入就可以了 import 你懂得