1,上传图片
1.1 前台显示页面:
<body>
<h1>struts图片的上传下载</h1>
<form action="${pageContext.request.contextPath }/sy/uploadAction_upload.action" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
1.2后台方法:
String name="####";这个地址一定要和你的图片名一模一样。保存和上传的方法中要一样
需要注意的是 <s:file name=“file”/>的name是什么
File file 就是什么
String fileContentType //就是加上ContentType
String fileFileName; // 加上FileName
package com.zking.interceptor;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import com.zking.four.web.BaseAction;
public class UploadAction extends BaseAction{
private File file;
private String fileContextType;
private String fileFileName;
private String serverDir = "/upload";
//上传图片
public String upload() {
System.out.println(file);
System.out.println(fileContextType);
System.out.println(fileFileName);
System.out.println("=====");
String realPath = getRealPath(serverDir + "/" +fileFileName);
System.out.println(realPath);
try {
FileUtils.copyFile(file, new File(realPath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
//本地的路径
private String getRealPath(String path) {
return application.getRealPath(path);
}
//打开图片
public String openAs() {
String type = "image/jpeg";
String name = "125E06BCDAA3AB235FE07865BF947B8A.jpg";
response.setContentType(type);
response.setHeader("Content-Disposition","filename=" + name);
File serverFile = new File(getRealPath(serverDir + "/" + name));
try {
FileUtils.copyFile(serverFile, response.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//保存
public String saveAs() {
String type = "image/jpeg";
String name = "125E06BCDAA3AB235FE07865BF947B8A.jpg.jpg";
response.setContentType(type);
response.setHeader("Content-Disposition","attachment;filename=" + name);//
File serverFile = new File(getRealPath(serverDir + "/" + name));
try {
FileUtils.copyFile(serverFile, response.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileContextType() {
return fileContextType;
}
public void setFileContextType(String fileContextType) {
this.fileContextType = fileContextType;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
}
前台页面
<body>
<h2>直接展示</h2>
<s:url var="openAsUrl" namespace="/sy" action="uploadAction_openAs"></s:url>
<img alt="" src='<s:property value="#openAsUrl"/>'>
<h2>保存图片</h2>
<s:url var="saveAsUrl" namespace="/sy" action="uploadAction_saveAs"></s:url>
<s:a href="%{#saveAsUrl}">保存图片</s:a>
<s:debug/>
</body>