struts 中的上传文件

页面写的是:

<form action="/bookmanager1.0/login.action" method="post" enctype="multipart/form-data">
<input type="file" name="file"> 
<input type="submit" value="上传">
</form>

Action中的代码是:

package com.lucas.action;


import java.text.SimpleDateFormat;


import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionSupport;
import java.io.*;
import java.util.*;


public class LoginAction extends ActionSupport {
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
String path=ServletActionContext.getRequest().getRealPath("/upload");
OutputStream os=null;
InputStream is=null;
try {
is=new FileInputStream(file);
Date nowdate=new Date();
SimpleDateFormat formate=new SimpleDateFormat("yyyyMMddHHmmss");
Random random=new Random();
int rannum=random.nextInt(1000);
String fileType=fileFileName.substring(fileFileName.lastIndexOf("."));
fileFileName=formate.format(nowdate)+rannum+fileType;

os=new FileOutputStream(new File(path,fileFileName));
byte[] b=new byte[1024];
int len=0;
while(-1 != (len=is.read(b))){
os.write(b, 0, len);
}

} catch (Exception e) {
// TODO: handle exception
}finally {
if(os != null){
os.close();
}
if(is!=null){
is.close();
}
}
return null;
}
private File file;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}


private String fileContentType;
private String fileFileName;
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
}

xml 中的配置就不谈了。。。



猜你喜欢

转载自blog.csdn.net/lu__ya/article/details/78942769