struts的文件上传与下载后台代码
package interceptor;
import java.io.File;
import java.io.IOException;import org.apache.commons.io.FileUtils;
import web.BaseAction;
/**
* 文件上传的三种方案:
* 1.将上传的文件以二进制的形式存放到数据库 oa系统 activiti工作框架
* 2.将文件上传到文件服务器(硬盘足够大,cpu转速快)中
* 3.将文件上传到tomcat所在的普通web服务器
* 真实路径与虚拟路径的概念
* 1.真实路径是指在自己电脑上能够看到的路径
* 2.虚拟在自己电脑看不到的路径
* @author ASUS
*/
public class UpladAction extends BaseAction {
private File file;//变量名指的是jsp的name属性,就是你要上传的文件
private String fileContenType;//文件类型
private String fileFileName;//文件名
private String servletDri="/upload";//你所指定得文件存放路径
//文件上传
public String upload() {
System.out.println(fileContenType);
System.out.println(fileFileName);
// 指的是Linux下的文件的所在位置
String realPath=getRealPath(servletDri+"/"+fileFileName);
System.out.println(realPath);
// 参数1:指的是本地图片文件,,参数2:在服务器生成的文件
try {
FileUtils.copyFile(file, new File(realPath));//表示从本地图片文件复制到服务器生成的文件
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
/**
* 获取Linux下的文件的所在位置
* @param path
* @return
*/
private String getRealPath(String path) {
// TODO Auto-generated method stub
return application.getRealPath(path);
}
public String openAs() {
String type="image/jpeg";//你要打开得图片类型
String name="333.jpg";//你要打开得文件名
response.setContentType(type);
response.setHeader("Content-Disposition","filename=" + name);
/**
* 将远程的图片输出到本地
* 数据源inputstream:远程new File(realPath)
* 目的:输出到本地得jsp:response.getOutputStream()
*/
指的是Linux下的文件的所在位置
String realPath=getRealPath(servletDri+"/"+name);
try {
FileUtils.copyFile(new File(realPath), response.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String download() {
String type="image/jpeg";
String name="333.jpg";
response.setContentType(type);
//文件下载中setHeader必须有attachment
response.setHeader("Content-Disposition","attachment;filename=" + name);
/**
* 将远程的图片输出到本地
* 数据源inputstream:远程new File(realPath)
* 目的:输出到本地得jsp:response.getOutputStream()
*/
// 指的是Linux下的文件的所在位置
String realPath=getRealPath(servletDri+"/"+name);
try {
FileUtils.copyFile(new File(realPath), 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 getFileContenType() {
return fileContenType;
}
public void setFileContenType(String fileContenType) {
this.fileContenType = fileContenType;
} public String getFileFileName() {
return fileFileName;
} public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
}