1.文件上传
1.1页面
<s:file name="upload" id="logoUpLoad"></s:file>
也可以用html的<file> 标签
1.2action
public String getFileRealPath(String filename){
String realPath = uploadPath;
if(StringUtils.isNotBlank(uploadDir)){
if(realPath.endsWith(File.separator)){
realPath = realPath+uploadDir;
}else{
realPath = realPath+"/"+uploadDir;
}
}
if(realPath.endsWith(File.separator)){
realPath = realPath+filename;
}else{
realPath = realPath+"/"+filename;
}
System.out.println("上传路径:"+realPath);
return realPath;
}
/**
* 上传文件
* @return
*/
public String uploadFiles(){
if(upload == null || upload.length == 0){
addActionError("要上传的文件不存在,请先选择文件再上传");
return ERROR;
}
// deleteFiles();
//获得上传文件的路径
uploadedFileNames = new String[upload.length];
try {
for (int i = 0; i < upload.length; i++) {
if(!upload[i].exists()){
continue;
}
String filename = uploadFileName[i];
String name = DateUtils.convertDate2String
("yyyy_MM_dd_hh_mm_ss", new Date())+"_"+System.currentTimeMillis()
+"."+com.cbsi.saas.util.SAASStringUtils.getExtension(filename, "");
File destFile = new File(getFileRealPath(name));
//需要引入jar
FileUtils.copyFile(upload[i], destFile);
uploadedFileNames[i] = name;
}
} catch (IOException e) {
addActionError("上传文件失败,请稍候重试");
log.error("上传文件失败",e);
return ERROR;
}
return SUCCESS;
}
private String uploadDir;//子目录
private String uploadPath;//要上传的目标文件夹
private File[] upload;//要上传的文件
private String[] uploadFileName; //上传的文件名 (1.系统自动注入 2.变量命名有规则: 前台对象名+"FileName")
private String[] uploadedFileNames;//上传后的文件名称
private String[] deleteOnUploadFileNames;//当上传的时候,同时要删除的文件名
private String downloadfile;//要下载的文件名
服务器图片页面显示
/**
* 下载图片
*
* @return
*/
public String loadEnterpriseLogo() {
System.out.println("downLoad enterprise logo");
// 获得上传文件的路径
try {
File file = new File(getFileRealPath(enterprise.getTrademark()));
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024 * 4];
int bytesRead = 0;
sout = ServletActionContext.getResponse().getOutputStream();
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
sout.write(buffer, 0, bytesRead);
}
fileInputStream.close();
sout.flush();
sout.close();
} catch (Exception e) {
}
return null;
}
<img
src="member/loadEnterpriseLogo.action?enterprise.trademark=${enterprise.trademark }"
width="450xp" height="150xp" />