//在这里 import 一些包
·································
public class UploadAction extends ActionSupport{
private File image; //上传的文件
private String imageFileName; //文件名称
private String imageContentType; //文件类型
private File image; //上传的文件
private String imageFileName; //文件名称
private String imageContentType; //文件类型
// getter 、setter 方法省略
public String execute() throws Exception {
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
//D:\apache-tomcat-6.0.18\webapps\struts2_upload\images
System.out.println("realpath: "+realpath);
if (image != null) {
File savefile = new File(new File(realpath), imageFileName);
if (!savefile.getParentFile().exists())
savefile.getParentFile().mkdirs();
FileUtils.copyFile(image, savefile);
ActionContext.getContext().put("message", "文件上传成功");
}
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
//D:\apache-tomcat-6.0.18\webapps\struts2_upload\images
System.out.println("realpath: "+realpath);
if (image != null) {
File savefile = new File(new File(realpath), imageFileName);
if (!savefile.getParentFile().exists())
savefile.getParentFile().mkdirs();
FileUtils.copyFile(image, savefile);
ActionContext.getContext().put("message", "文件上传成功");
}
文件上传有三种上传方式,这里写的是copy的方式,
另外两种是
1.按字节方式上传:
- public String uploadFile(){
- /** 文件的写操作 */
- FileInputStream fis = null;
- FileOutputStream fos = null;
- /** 保存的路径 */
- String savepath = getSavePath();
- /** 根据保存的路径创建file对象 */
- File file = new File(savepath);
- /** file对象是否存在 */
- if (!file.exists()) {
- /** 创建此文件对象路径 */
- file.mkdirs();
- }
- try {
- /** 创建输入流 */
- fis = new FileInputStream(pic);
- /** 输出流 更据文件的路径+文件名称创建文件对象 */
- fos = new FileOutputStream(file + "//" + getPicFileName());
- /** 读取字节 */
- byte b[] = new byte[1024];
- int n = 0;
- /** 读取操作 */
- while ((n = fis.read(b)) != -1) {
- /** 写操作 */
- fos.write(b, 0, n);
- }
- /** 关闭操作 */
- if (fis != null) {
- fis.close();
- }
- if (fos != null) {
- fos.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return SUCCESS;
- }
- 2.按字符方式上传 即“三层管道”
- public String uploadFile(){
- /** 文件的写操作 */
- BufferedReader br =null;
- BufferedWriter bw = null;
- /** 保存的路径 */
- String savepath = getSavePath();
- /** 根据保存的路径创建file对象 */
- File file = new File(savepath);
- /** file对象是否存在 */
- if (!file.exists()) {
- /** 创建此文件对象路径 */
- file.mkdirs();
- }
- try {
- /** 创建一个BufferedReader 对象*/
- br = new BufferedReader(new InputStreamReader(new FileInputStream
- (pic)));
- bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream
- (file + "//" + getPicFileName())));
- // 读取字节
- char b[] = new char[1024];
- int n = 0;
- // 读取操作
- while ((n = br.read(b)) != -1) {
- // 写操作
- bw.write(b, 0, n);
- }
- // 关闭操作
- if (br != null) {
- br.close();
- }
- if (bw != null) {
- bw.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return SUCCESS;
- }