servlet中怎样获得页面传来的文件?

zxlion 2009-07-09 11:44:22
不用框架,第三方组件,纯servlet。
...全文
给本帖投票
797 13 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
b47248054 2009-07-09
  • 打赏
  • 举报
回复
可以用servletinputstream进行处理;

txf_7337 2009-07-09
  • 打赏
  • 举报
回复

public ActionForward execute(HttpServletRequest request,
HttpServletResponse reponse) throws Exception {
ActionForward forward = new ActionForward("/fail.go");
HttpSession session = request.getSession();

DiskFileItemFactory dfif = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(dfif);
upload.setSizeMax(5 * 1024 * 1024);

List list = upload.parseRequest(request);
if (list.size() > 0) {
FileItem item = (FileItem) list.get(0);
String name = item.getName();
String path = "/pic/" + name;

// 实现图片上传
item.write(new File(getServletContext().getRealPath(path)));
ActionForward forward = new ActionForward("/success.go");
}
forward.setRedirect(true);
return forward;

}
网络精灵 2009-07-09
  • 打赏
  • 举报
回复
就算不用第三方组件,最好还是用流传送,form有个属性enctype="multipart/form-data",到servlet解析就行了。可以参考apache的fileupload
chen7788 2009-07-09
  • 打赏
  • 举报
回复
你用什么对象传过来,就用对象接收不就得了。
kadach11 2009-07-09
  • 打赏
  • 举报
回复
页面传来的文件:
取得 file 参数,用流读出来。

页面传来的值:
更简单,requset.getP.........
meander 2009-07-09
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 ltandfyy 的回复:]
纯servlet你要解析原request,在没有任何框架和第三方控件的情况下request的格式你要非常清楚,转换成流时是什么样的形式,起始符,分隔符,终止符,都要搞清楚才能动手解析,而且要满足各种类型的文件上传,确实不是很容易,我上个项目中用到了,把源码给你,但暂时只能上传单个文件,如果是多个文件,你先看懂下面的代码,再做改进,因为这时会出现多个文件之间分隔符的解析问题,单个文件比较简单,而且这个代码中我还没有做判…
[/Quote]

不错
ltandfyy 2009-07-09
  • 打赏
  • 举报
回复
哦,代码中的import com.hoperun.e2.util.StringUtil;包你不用管它,这是我们项目中用的生成唯一随机主键的包。
code_killer 2009-07-09
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 hsf_1982 的回复:]
不要太勉强,如果什么都自己开发,那干嘛用Java开发呢,还不如去搞C呢。
commons-fileupload.jar是apache的开源项目,虽然没几个类,但提供了web服务器解析上传文件的一整套的解决方案吧。建议继承“拿来主义”,当然没事干也可以反编译看看。
[/Quote]

晕,既然是开源项目,干嘛还要反编译?
ltandfyy 2009-07-09
  • 打赏
  • 举报
回复
文件太大,一次没发完,接着的:

//存上传的文件
private boolean writeFile(byte[] data, String path) {
File f = null;
FileOutputStream fos = null;
try {
f = new File(path);
f.createNewFile();
fos = new FileOutputStream(f);
fos.write(data, 0, data.length);
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
} finally {
try {
if(fos != null) {
fos.flush();
fos.close();
}
} catch (IOException e) {
return false;
}
}
return true;
}

//取得文件名
private String getFileName(String arg) {
String path = "";
if(arg.equals("\"\"")) {
return null;
}

if (arg.indexOf("\"") > -1)
path = arg.substring(arg.indexOf("\"") + 1, arg.lastIndexOf("\""));
else
path = arg;
path = path.substring(path.lastIndexOf("\\") + 1);
return path;
}


//判断两个byte数组的值是否相等
private boolean arrayEquals(byte[] src, byte[] value){
if(src == null || value == null)
return false;
if(src.length != value.length)
return false;

for(int i=0; i<src.length; i++) {
if(src[i] != value[i])
return false;
}
return true;
}


//找出value数组在src中的位置, 从前往后
private int arrayIndexOf(byte[] src, byte[] value){
if(src == null || value == null)
return -1;
if(src.length < value.length)
return -1;

int postion = -1;

for(int i=0; i<src.length - value.length; i++) {
postion = i;
byte[] tmp = new byte[value.length];
System.arraycopy(src, i, tmp, 0, tmp.length);
if(arrayEquals(tmp, value)) {
tmp = null;
return postion;
}else{
postion = -1;
tmp = null;
}
}

return postion;
}


//找出value数组在src中的位置
private int arrayLastIndexOf(byte[] src, byte[] value){
if(src == null || value == null)
return -1;
if(src.length < value.length)
return -1;

int postion = -1;

for(int i=src.length - value.length ; i >-1; i--) {
postion = i;

byte[] tmp = new byte[value.length];
System.arraycopy(src, i, tmp, 0, tmp.length);
if(arrayEquals(tmp, value)) {
tmp = null;
return postion;
}else{
postion = -1;
tmp = null;
}
}
return postion;
}

private HashMap<String, String> parseAnotherParam(String str){
HashMap<String, String> hm= new HashMap<String, String>();
String key="";
String value="";
int startindex = 0;
int endindex = 0;

startindex = str.indexOf("Content-Disposition: form-data; name=\"")
+ "Content-Disposition: form-data; name=\"".length();
endindex = str.indexOf("\"\r\n\r\n");

while ( startindex >-1 && endindex > -1 ){
key = str.substring(startindex, endindex);

if(!str.substring(endindex , endindex + 5).equals("\"\r\n\r\n") ){//去掉没有value的元素
str = str.substring(endindex);
startindex = str.indexOf("Content-Disposition: form-data; name=\"")
+ "Content-Disposition: form-data; name=\"".length();
endindex = str.indexOf("\"\r\n\r\n");
continue;
}
if( key.indexOf("\";") > -1){//去掉上传文件的参数以及编码
str = str.substring(str.indexOf("\";") + 2);
startindex = str.indexOf("Content-Disposition: form-data; name=\"")
+ "Content-Disposition: form-data; name=\"".length();
endindex = str.indexOf("\"\r\n\r\n");

continue;
} else
str = str.substring(endindex + 5);

value = str.substring(0, str.indexOf("\r\n"));
str = str.substring(str.indexOf("\r\n") + 2);
hm.put(key,value);

startindex = str.indexOf("Content-Disposition: form-data; name=\"")
+ "Content-Disposition: form-data; name=\"".length();
endindex = str.indexOf("\"\r\n\r\n");

}
return hm;
}
}
ltandfyy 2009-07-09
  • 打赏
  • 举报
回复
纯servlet你要解析原request,在没有任何框架和第三方控件的情况下request的格式你要非常清楚,转换成流时是什么样的形式,起始符,分隔符,终止符,都要搞清楚才能动手解析,而且要满足各种类型的文件上传,确实不是很容易,我上个项目中用到了,把源码给你,但暂时只能上传单个文件,如果是多个文件,你先看懂下面的代码,再做改进,因为这时会出现多个文件之间分隔符的解析问题,单个文件比较简单,而且这个代码中我还没有做判断,判断文件与别的控件值同时提交的问题,如果还有别的参数提交,是肯定要分析的,因为request获取到的流仅一次,你在截取到的时候不分析取到parameter,就再也取不到了,而且因为要上传文件的原因,页面form变成了enctype="multipart/form-data",这时servlet中getParameter是取不到任何东西的,全在流中,框架下之所以能取到,是因为框架处理过了,你先研究一下这个吧:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.Servlet;

import com.hoperun.e2.util.StringUtil;

@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet implements Servlet{
//允许上传文件的最大M数
public static final int MAX_SIZE = 1024 * 1024 * 100;
//存放上传文件的子目录
private static final String DIR = "UploadFiles/";
//存放运行WEB工程的根路径
private String FILE_DIR;
private int file_Size=0;
private String file_Path = "";
private HashMap<String, String> hm = new HashMap<String, String>();
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) {
doPost(request,response);
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) {
String path = this.getServletConfig().getServletContext().getRealPath("/");
FILE_DIR = path.replaceAll("\\\\", "/") + DIR;
String result = upload(request);
PrintWriter out = null;
try {
response.setContentType("text/html;charset=UTF-8");
out = response.getWriter();
out.print(result);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(out != null) {
out.flush();
out.close();
}
}
}
//上传文件
private String upload(HttpServletRequest req) {
String tmpString ="";
String result = "";
DataInputStream dis = null;
try {
dis = new DataInputStream(req.getInputStream());
String content = req.getContentType();
if (content != null && content.indexOf("multipart/form-data") != -1) {
int reqSize = req.getContentLength();
byte[] data = new byte[reqSize];

int bytesRead = 0;
int totalBytesRead = 0;
int sizeCheck = 0;
while (totalBytesRead < reqSize) {
// check for maximum file size violation
sizeCheck = totalBytesRead + dis.available();
if (sizeCheck > MAX_SIZE)
result = "文件太大不能上传...";
bytesRead = dis.read(data, totalBytesRead, reqSize);
totalBytesRead += bytesRead;
}
tmpString = new String(data);
hm = parseAnotherParam(tmpString);
int postion = arrayIndexOf(data, "\r\n".getBytes());
byte[] split_arr = new byte[postion];
System.arraycopy(data, 0, split_arr, 0, postion);

postion = arrayIndexOf(data, "filename=\"".getBytes());
byte[] dataTmp = new byte[data.length - postion];
System.arraycopy(data, postion, dataTmp, 0, dataTmp.length);
data = null;
data = dataTmp.clone();
String filePath =null;
postion = arrayIndexOf(data, "Content-Type:".getBytes())-2;
dataTmp = null;
dataTmp = new byte[postion];
System.arraycopy(data, 0, dataTmp, 0, dataTmp.length);
filePath = new String(dataTmp);
if (filePath==null && filePath.equals("")) return "";
// 分离contentType 并赋值
postion = arrayIndexOf(data, "Content-Type:".getBytes());
dataTmp = null;
dataTmp = new byte[data.length - postion];
System.arraycopy(data, postion, dataTmp, 0, dataTmp.length);
data = null;
data = dataTmp.clone();
postion = arrayIndexOf(data, "\n".getBytes()) + 1;
dataTmp = null;
dataTmp = new byte[data.length - postion];
System.arraycopy(data, postion, dataTmp, 0, dataTmp.length);
data = null;
data = dataTmp.clone();

// 分离文件信息 获得最终想要的字节
postion = arrayIndexOf(data, split_arr);
split_arr = null;
dataTmp = null;
dataTmp = new byte[postion - 2];
System.arraycopy(data, 2, dataTmp, 0, dataTmp.length);
data = null;
data = dataTmp.clone();

postion = arrayLastIndexOf(data, "\n".getBytes())-1;
dataTmp = null;
dataTmp = new byte[postion];
System.arraycopy(data, 0, dataTmp, 0, dataTmp.length);

data = null;
String fileName = getFileName(filePath);
String UUID = StringUtil.makeUUID();
if(null != fileName) {
File file = new File(FILE_DIR);
boolean existsFlag = false;
if(!(existsFlag = file.exists())) {
existsFlag = file.mkdirs();
}
//对文件名做处理,用唯一标识符代替原文件名,后缀名保留
int lastIndex = fileName.lastIndexOf(".");
if(lastIndex == -1) {
fileName = UUID;
} else {
fileName = UUID + fileName.substring(lastIndex, fileName.length());
}
if (writeFile(dataTmp, FILE_DIR + fileName) && existsFlag) {
this.file_Size = dataTmp.length;
this.file_Path = FILE_DIR + fileName;
result = "文件上传完毕." + DIR + fileName;
} else {
result = "文件上传失败";
}
} else {
result = "文件名为空";
}
dataTmp = null;
} else {
result = "content 必须为 multipart/form-data";
}
} catch (UnsupportedEncodingException ex4) {
result = "UnsupportedEncodingException错误";
} catch (NullPointerException e) {
result = "NullPointerException错误";
} catch (IOException ex1) {
result = "IOException 错误 ";
}catch (Exception ex1) {
result = "Exception 错误 ";
} finally {
if(dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}

jinchun1234 2009-07-09
  • 打赏
  • 举报
回复

1upload,jsp文件如下:

<form action="servlet/Upload" method="post">
<input type="file" name="file1">
<br>
<input type="file" name="file2">
<br>
<input type="file" name="file3">
<input type="submit" value="upload" />
<br>
<br>
<a href="servlet/down?downFile=入门教程.doc">down</a>
</form>

2、在servlet(Upload.java)中的dopost中写代码如下:

response.setContentType("text/html; charset=gb2312");
// 要下载的文件名
// 之所以这样处理,主要是因为文件名的中文化问题,这样处理的话,中文文件名也会正常显示
String aa=new String((request.getParameter("file1"))
.getBytes("iso8859-1"), "gb2312");
String bb=new String((request.getParameter("file2"))
.getBytes("iso8859-1"), "gb2312");
String cc=new String((request.getParameter("file3"))
.getBytes("iso8859-1"), "gb2312");
List<String> list = new ArrayList<String>();
if(aa!=null || !aa.equals(""))
list.add(aa);
if(!bb.equals("") || bb!=null)
list.add(bb);
if(cc!=null || !cc.equals(""))
list.add(cc);
// 建立上传文件存放的路径
File uploadPath = new File(request.getRealPath("/downloadPath") );
System.out.println(uploadPath );
if (!uploadPath.exists()) {
uploadPath.mkdirs();
}
for (int i = 0; i < list.size(); i++) {
String fileName[] = new String[list.size()];
String exFileName[] = new String[list.size()];
// 文件路径
String filePath = list.get(i);
// 取上传的文件名称
fileName[i] = filePath.substring(filePath.lastIndexOf("\\") + 1,
filePath.length());
// 取文件的扩展名称
// exFileName[i] = filePath.substring(filePath.lastIndexOf("." + 1,
// filePath.length()));
// 在存放的目录下新建文件
File uploadFileName = new File(uploadPath, fileName[i]);
if (!uploadFileName.exists()) {
uploadFileName.createNewFile();
}
FileInputStream fin=new FileInputStream(filePath);
// 向服务器写入文件
java.io.FileOutputStream fos = new java.io.FileOutputStream(uploadPath + "/" + fileName[i]);
int c = fin.read();
while (c != -1) {
fos.write((char)c);
c=fin.read();
}
fin.close();
fos.close();
}

老张-AI 2009-07-09
  • 打赏
  • 举报
回复
request.getPar..
用这个接收
hsf_1982 2009-07-09
  • 打赏
  • 举报
回复
不要太勉强,如果什么都自己开发,那干嘛用Java开发呢,还不如去搞C呢。
commons-fileupload.jar是apache的开源项目,虽然没几个类,但提供了web服务器解析上传文件的一整套的解决方案吧。建议继承“拿来主义”,当然没事干也可以反编译看看。

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧

手机看
关注公众号

关注公众号

客服 返回
顶部