Struts2 上传实例六种方法(去除了jar包,配置时必须导入包:
commons-fileupload-1.2.1.jar;commons-io-1.3.2.jar;commons-logging-1.0.4.jar;
freemarker-2.3.13.jar;ognl-2.6.11.jar;struts2-core-2.1.6.jar;xwork-2.1.2.jar
补充:
Struts2Upload(全含jar包,将数据保存到数据库)
压缩包部分代码如下(方法一、方法三):
public String execute() throws Exception {
InputStream is=new FileInputStream(filer);
String root=ServletActionContext.getRequest().getRealPath("/upload");
File destFile=new File(root,this.getFileFileName());
OutputStream os=new FileOutputStream(destFile);
byte[] buffer=new byte[400];
byte t;
int length=0;
while((length=is.read(buffer))>0)
{
os.write(buffer,0,length);
}
/*UploadService us=new UploadService();
int flag=us.insertUpload(filmName, filmContent,filer);*/
is.close();
os.close();
return SUCCESS;
}
private static void copy(File src, File dst) {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public String execute() throws Exception {
//根据服务器的文件保存地址和原文件名创建目录文件全路径
String dstPath = ServletActionContext.getServletContext()
.getRealPath("/upload")
+ "\\" + uploadFileName;
System.out.println("上传的文件的类型:"+ this.getUploadContentType());
File dstFile = new File(dstPath);
copy(this.upload, dstFile);
return SUCCESS;
}
本文系个人总结,能够实现功能,非网上搜索!!!