求一个用struts处理多文件上传的例子?

tsqqq 2004-06-24 10:32:34
用struts自带的包org.apache.struts.upload.FormFile;
我现在的主要问题是如何在ActionForm里面得到所上传的多文件的数组,请指点一下,谢谢!
...全文
276 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
sunrisefe 2004-07-30
  • 打赏
  • 举报
回复
rer
tsqqq 2004-06-30
  • 打赏
  • 举报
回复
to zpxocivuby(荒原困兽):
老兄,你真是太叼了 ,让小弟我实在是佩服;
不过这段代码你真的调试过吗,是不是觉得是数组就用FormFile[]可以搞定,你这样做是不是有点太想当然了,如果是像这样的话我恐怕也不用来这里发帖子了。
其实这个问题关键在于ActionForm而不是Action,只要得到在ActionForm里面得到了数据,Action里面是很简单的,在example里面就有;
现在这个问题我这里已经有一些突破,希望早点解决后能与大家分享
discolt 2004-06-29
  • 打赏
  • 举报
回复
public String uploadPlusfile(UploadForm form, String uploadPath,
HttpServletRequest request) throws FileNotFoundException,
IOException {

String path = uploadPath;
path += "/" + form.getPlusPath();
new File(path).mkdirs();
StringBuffer sb = new StringBuffer();

// 得到附件
List otherFiles = new ArrayList();
if (form.getFile1() != null && form.getFile1().getFileSize() > 0) {
otherFiles.add(form.getFile1());
}
if (form.getFile2() != null && form.getFile2().getFileSize() > 0) {
otherFiles.add(form.getFile2());
}
if (form.getFile3() != null && form.getFile3().getFileSize() > 0) {
otherFiles.add(form.getFile3());
}
if (form.getFile4() != null && form.getFile4().getFileSize() > 0) {
otherFiles.add(form.getFile4());
}
if (form.getFile5() != null && form.getFile5().getFileSize() > 0) {
otherFiles.add(form.getFile5());
}
if (form.getFile6() != null && form.getFile6().getFileSize() > 0) {
otherFiles.add(form.getFile6());
}
if (form.getFile7() != null && form.getFile7().getFileSize() > 0) {
otherFiles.add(form.getFile7());
}
if (form.getFile8() != null && form.getFile8().getFileSize() > 0) {
otherFiles.add(form.getFile8());
}
if (form.getFile9() != null && form.getFile9().getFileSize() > 0) {
otherFiles.add(form.getFile9());
}
if (form.getFile10() != null && form.getFile10().getFileSize() > 0) {
otherFiles.add(form.getFile10());
}
if (form.getFile11() != null && form.getFile11().getFileSize() > 0) {
otherFiles.add(form.getFile11());
}
if (form.getFile12() != null && form.getFile12().getFileSize() > 0) {
otherFiles.add(form.getFile12());
}
if (form.getFile13() != null && form.getFile13().getFileSize() > 0) {
otherFiles.add(form.getFile13());
}
if (form.getFile14() != null && form.getFile14().getFileSize() > 0) {
otherFiles.add(form.getFile14());
}
if (form.getFile15() != null && form.getFile15().getFileSize() > 0) {
otherFiles.add(form.getFile15());
}
if (form.getFile16() != null && form.getFile16().getFileSize() > 0) {
otherFiles.add(form.getFile16());
}
if (form.getFile17() != null && form.getFile17().getFileSize() > 0) {
otherFiles.add(form.getFile17());
}
if (form.getFile18() != null && form.getFile18().getFileSize() > 0) {
otherFiles.add(form.getFile18());
}
if (form.getFile19() != null && form.getFile19().getFileSize() > 0) {
otherFiles.add(form.getFile19());
}
if (form.getFile20() != null && form.getFile20().getFileSize() > 0) {
otherFiles.add(form.getFile20());
}

// 上传附件
for (Iterator it = otherFiles.iterator(); it.hasNext();) {
FormFile otherFile = (FormFile) it.next();
InputStream is2 = otherFile.getInputStream();
String writeOtherPath = path + "/" + otherFile.getFileName();
BufferedOutputStream bos2 = new BufferedOutputStream(
new FileOutputStream(writeOtherPath));
FileIO.copyFile(is2, bos2, true);
sb.append("附件:" + otherFile.getFileName() + "上传成功!");
}
return sb.toString();
}
tsqqq 2004-06-28
  • 打赏
  • 举报
回复
d
jamesqsj 2004-06-28
  • 打赏
  • 举报
回复
study
zpxocivuby 2004-06-28
  • 打赏
  • 举报
回复


package org.apache.struts.webapp.upload;


import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;



/**
* This class takes the UploadForm and retrieves the text value
* and file attributes and puts them in the request for the display.jsp
* page to display them
*
* @author Mike Schachter
* @version $Revision: 1.8 $ $Date: 2003/02/28 02:18:23 $
*/


public class UploadAction extends Action
{
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {

if (form instanceof UploadForm) {
int SIZE_OF_ARRYLIST = 2;
//this line is here for when the input page is upload-utf8.jsp,
//it sets the correct character encoding for the response
String encoding = request.getCharacterEncoding();
if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8")))
{
response.setContentType("text/html; charset=utf-8");
}

UploadForm theForm = (UploadForm) form;

//retrieve the text data
String text = theForm.getTheText();

//retrieve the query string value
String queryValue = theForm.getQueryParam();

//retrieve the file representation
FormFile[] file = new FormFile[SIZE_OF_ARRYLIST];
file[0]=theForm.getFile1();
file[1]= theForm.getfile2();
//retrieve the file name
for (int i =0;i<SIZE_OF_ARRYLIST;i++){
String fileName= file[i].getFileName();

//retrieve the content type
String contentType = file[i].getContentType();

boolean writeFile = theForm.getWriteFile();

//retrieve the file size
String size = (file[i].getFileSize() + " bytes");

String data = null;

try {
//retrieve the file data
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream stream = file[i].getInputStream();
if (!writeFile) {
//only write files out that are less than 1MB
if (file[i].getFileSize() < (4*1024000)) {

byte[] buffer = new byte[8192];
int bytesRead = 0;
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
baos.write(buffer, 0, bytesRead);
}
data = new String(baos.toByteArray());
}
else {
data = new String("The file is greater than 4MB, " +
" and has not been written to stream." +
" File Size: " + file[i].getFileSize() + " bytes. This is a" +
" limitation of this particular web application, hard-coded" +
" in org.apache.struts.webapp.upload.UploadAction");
}
}
else {
//write the file to the file specified
OutputStream bos = new FileOutputStream(theForm.getFilePath());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
data = "The file has been written to \"" + theForm.getFilePath() + "\"";
}
//close the stream
stream.close();
}
catch (FileNotFoundException fnfe) {
return null;
}
catch (IOException ioe) {
return null;
}

//place the data into the request for retrieval from display.jsp
request.setAttribute("text", text);
request.setAttribute("queryValue", queryValue);
request.setAttribute("fileName"+i, fileName);
request.setAttribute("contentType", contentType);
request.setAttribute("size", size);
request.setAttribute("data", data);
}
//destroy the temporary file created
file.destroy();

//return a forward to display.jsp
return mapping.findForward("display");
}

//this shouldn't happen in this example
return null;
}
}
上面的程序发错了,不过也是一个很好的vb实现的方式,遇到问题多动动脑子,懒人!
zpxocivuby 2004-06-28
  • 打赏
  • 举报
回复
client.htm

<html>
<head>
</head>
<body>
<input type=button onclick="BeginSendFiles();" value="发送" />
<input type=button onclick="javascript: Breaked=true;" value="中断" />
<div id="ddd" width=300px></div>
<br></br>
<DIV id=div_message></DIV>
</body>

<script language=VBScript>
Function bytes2BSTR(vIn)
strReturn = ""
For i = 1 To LenB(vIn)
ThisCharCode = AscB(MidB(vIn,i,1))
If ThisCharCode < &H80 Then
strReturn = strReturn & Chr(ThisCharCode)
Else
NextCharCode = AscB(MidB(vIn,i+1,1))
strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(NextCharCode))
i = i + 1
End If
Next
bytes2BSTR = strReturn
End Function
</script>

<script language=javascript>
var xmlhttp ;
var ado_stream ;
var mFileName, mPartStart, mPartID, mPartEnd ;
var SendCount ;
var BlockSize ;
var Breaked ;
var aryFiles ;

BlockSize = 1024*100 ;
Breaked = false ;
aryFiles = new Array() ;

// 开始发送文件
function BeginSendFiles()
{
initAryFiles() ;
SendFile(aryFiles.pop()) ;
}

// 构造待发送文件的数组
function initAryFiles()
{
aryFiles.push("c:\\tmp\\myfile.doc") ;
aryFiles.push("c:\\tmp\\myfile555.doc") ;
aryFiles.push("c:\\tmp\\myfile111.doc") ;

aryFiles.reverse() ;
}

function SendFile(vFullPath)
{
// 空文件则不执行上传
if (!vFullPath)
{
return ;
}

Breaked = false ;
div_message.innerHTML = "" ;
ado_stream = new ActiveXObject("ADODB.Stream"); // 读取文件的流
ado_stream.Type = 1;
ado_stream.Open();
ado_stream.LoadFromFile(vFullPath); // 读取文件
ado_stream.position = 0 ;

SendCount = Math.ceil(ado_stream.size/BlockSize) ; // 如果有余数则多发送一次

// alert(SendCount) ;

var reg = /\b\w+.\w+$/gi
mFileName = reg.exec(vFullPath) ;
mPartStart = true ;
mPartID = 1 ;
mPartEnd = false ;

SendData() ;
}

function SendData()
{
if (SendCount > 0)
{
var dom = new ActiveXObject("msxml2.DOMDocument"); // 发送的xml文件
dom.async = false;
dom.resolveExternals = false;

// 构造xml文件头
var node = dom.createProcessingInstruction("xml","version='1.0'");
dom.appendChild(node) ;
node = null ;

// 构造root节点
var root = dom.createElement("root");
dom.appendChild(root) ;
dom.documentElement.setAttribute("xmlns:dt", "urn:schemas-microsoft-com:datatypes");

// 构造保存二进制数据的节点updata
node = dom.createElement("upData") ;
node.dataType = "bin.base64" ; // bin。base64编码
var att = dom.createAttribute("FileName") ; // 文件名属性
att.value = mFileName ;
node.setAttributeNode(att) ;
att = null ;
var att = dom.createAttribute("PartStart") ; // 分段开始标记
att.value = mPartStart ;
node.setAttributeNode(att) ;
att = null ;
var att = dom.createAttribute("PartID") ; // 分段序号
att.value = mPartID ;
node.setAttributeNode(att) ;
att = null ;
var att = dom.createAttribute("PartEnd") ; // 分段结束标记
att.value = mPartEnd ;
node.setAttributeNode(att) ;
att = null ;

root.appendChild(node) ;
node.nodeTypedvalue = ado_stream.Read(BlockSize); // 节点数据从stream读取,固定长度
node = null ;

SendCount -= 1 ;
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("POST","http://192.168.1.100/tst.asp";, false);
xmlhttp.onreadystatechange= CallBack ;
xmlhttp.send(dom);

mPartStart = false ;
xmlhttp = null ;
}
else
{
ado_stream.Close();
ado_stream = null ;
}

}

function CallBack()
{
// 上传成功
if(xmlhttp.readystate == 4)
{
// 检查是否中断上传
if(Breaked)
{
return ;
}

if (SendCount > 0)
{
mPartID += 1 ;
// div_message.innerHTML += ("<br>" + xmlhttp.ResponseText) ;

var p = Math.floor((mPartID/(Math.ceil(ado_stream.size/BlockSize) + 1)) * 100) ; // 计算进度百分比
ShowBar(p) ;

var t = setTimeout("SendData();", 1) ;
}
else
{
// 传送完文件
//div_message.innerHTML += mFileName + "传送完毕!<br>" ;

// 继续传下一文件
ShowBar(0) ;
var cFile = aryFiles.pop() ;
SendFile(cFile) ;
}

}


}

function ShowBar(per)
{
// 进度条
ddd.innerHTML = "<table width='200' border=0 cellpadding='0' cellspacing='0' ><tr><td bgcolor='#6699FF'><input type=button style=' width:" + per + "% ; border:0px; background:#005599; color:#FFFFFF' value=" + per + "%> </td></tr></table>" ;
}

</script>
</html>



server.asp

<%@ LANGUAGE=VBScript%>
<% Option Explicit
Response.Expires = 0

' 定义变量和对象。
dim ado_stream
dim xml_dom
dim xml_data
dim str_filename
dim bol_PartStart
dim int_PartID
dim bol_PartEnd

' 创建 Stream 对象
set ado_stream = Server.CreateObject("ADODB.Stream")
' 从Request对象创建 XMLDOM对象
set xml_dom = Server.CreateObject("MSXML2.DOMDocument")
xml_dom.load(request)
' 读出包含二进制数据的节点
set xml_data = xml_dom.selectSingleNode("root/upData")
str_filename = xml_data.getAttribute("FileName")
bol_PartStart = CBool(xml_data.getAttribute("PartStart"))
int_PartID = CInt(xml_data.getAttribute("PartID"))
bol_PartEnd = CBool(xml_data.getAttribute("PartEnd"))

' 打开Stream对象,把数据存入其中
ado_stream.Type = 1 ' 1=adTypeBinary
ado_stream.open
if not bol_PartStart then
ado_stream.LoadFromFile("c:\\tmp\\get\\" + str_filename) // 读取文件
ado_stream.position = ado_stream.size
end if
ado_stream.Write xml_data.nodeTypedvalue
' 文件存盘
ado_stream.SaveToFile "c:\\tmp\\get\\" + str_filename,2 ' 2=adSaveCreateOverWrite
ado_stream.close

' 销毁对象
set ado_stream = Nothing
set xml_dom = Nothing
' 向浏览器返回信息
Response.Write "Upload successful!"& str_filename & int_PartID & bol_PartStart
%>
tsqqq 2004-06-25
  • 打赏
  • 举报
回复
d
tsqqq 2004-06-25
  • 打赏
  • 举报
回复
to zpxocivuby(荒原困兽):
高人,我这里也有例子 ,不过是单文件上传的,你有多文件的可以给我看看,我说了要用数组来处理 谢谢
zpxocivuby 2004-06-25
  • 打赏
  • 举报
回复
去看example吧懒人
TIANHEI 2004-06-25
  • 打赏
  • 举报
回复
up

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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