Struts图片上传

Struts图片上传

1.文件上传的三种方式

  • 上传到tomcat服务器 不推荐
    缺点:
    1 有时候上传后需要刷新一遍,图片才会出来
    2 重启tomcat图片可能会丢失
  • 上传到指定文件目录,添加服务器与真实目录的映射关系,从而解耦上传文件与tomcat的关系文件服务器
  • 在数据库表中建立二进制字段,将图片存储到数据库 (淘汰)

2.以第二点为案例
upload.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>班级logo上传界面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/sy/clazz_upload.action" method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit" value="ok">
</form>
</body>
</html>

配置struts-sy.xml:

<result name="preUpload">/clzUpload.jsp</result>

在控制器ClazzAction中添加方法:

package com.su.three.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ModelDriven;
import com.su.three.dao.ClazzDao;
import com.su.three.entity.Clazz;
import com.su.three.util.BaseAction;
import com.su.three.util.PageBean;

public class ClazzAction extends BaseAction implements ModelDriven<Clazz>{
	private ClazzDao clazzDao=new ClazzDao();
	private Clazz clazz=new Clazz();
	private File file;//<input type="file" name="file">中的name对应的属性值
	private String fileFileName;
	private String fileContentType;
	
	
	/**
	 * @return
	 * 跳转上传页面
	 */
	public String preUpload() {
		try {
			this.result=clazzDao.list(clazz, null).get(0);
		} catch (InstantiationException | IllegalAccessException | SQLException e) {
			e.printStackTrace();
		}
		return "preUpload";
	}
	
	/**
	 * @return
	 * 处理上传发送的请求
	 */
	public String upload(){
		//图片存放的真实目录
		String realDir="D:/图片";
		String serverDir="/upload";
		try {
			//将本地图片上传到服务器的某一真实存在的目录(从本地读取文件写入到服务器)
//			FileUtils.copyFile(file, new File(realDir+"/"+fileFileName));
			copyFile(file, new File(realDir+"/"+fileFileName));
			clazz.setPic(serverDir+"/"+fileFileName);
			this.clazzDao.edit(clazz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toList";
	}
	
	/**
	 * @param source
	 * @param target
	 * 从本地读取文件写入到服务器
	 * @throws FileNotFoundException 
	 */
	private void copyFile(File source,File target) throws IOException {
		BufferedInputStream in=new BufferedInputStream(new FileInputStream(source));
		BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(target));
		byte [] bbuf=new byte[1024];
		int len=0;
		while((len=in.read(bbuf))!=-1) {
			out.write(bbuf,0,len);
		}
		in.close();
		out.close();
	}
	
	/**
	 * @return
	 * 查看班级信息
	 */
	public String list() {
	    PageBean pageBean=new PageBean();
	    pageBean.setRequest(request);
	    try { 
			this.result=clazzDao.list(clazz, pageBean);//result值栈的赋值
			request.setAttribute("pageBean", pageBean);
		} catch (InstantiationException | IllegalAccessException | SQLException e) {
			e.printStackTrace();
		}
		return "list";
	}
	
    /**
     * @return
     * 跳转编辑页面(新增编辑是同一页面)
     */
    public String preSave() {
		//跳转新增页面和编辑页面的区别在于跳转编辑页面的时候要传cid到后台进行查询,并且将查询到的内容回显
    	int cid=clazz.getCid();
    	if(cid!=0) {
    		try {
				this.result=clazzDao.list(clazz, null).get(0);
			}catch (InstantiationException | IllegalAccessException | SQLException e) {
				e.printStackTrace();
			}
    	}
		return "preSave";
	}

    /**
     * @return
     * 新增班级信息
     */
    public String add() {
	try {
		this.code=this.clazzDao.add(clazz);
	} catch (IllegalArgumentException | IllegalAccessException | SQLException e) {
		e.printStackTrace();
	}
	return "toList";
}

    /**
     * @return
     * 删除班级信息
     */
    public String del() {
    	try {
    		this.code=this.clazzDao.del(clazz);
    	} catch (IllegalArgumentException | IllegalAccessException | SQLException e) {
    		e.printStackTrace();
    	}
    	return "toList";
}

    /**
     * @return
     * 修改班级信息
     */
    public String edit() {
    	try {
    		this.code=this.clazzDao.edit(clazz);
    	} catch (IllegalArgumentException | IllegalAccessException | SQLException e) {
    		e.printStackTrace();
    	}
    	return "toList";
}

	@Override
	public Clazz getModel() {
		return clazz;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	
	

}


添加服务器与真实目录的映射关系(Servers下的server.xml):

<Context docBase="D:/图片" path="/web_struts/upload"/>
<!-- docBase:真实路径    path:项目名+upload页面 -->

图片上传图:
在这里插入图片描述

/* * 使用java.util.Map接口实现文件组的上传 */ private void muchUploadFile(IndexActionForm objForm) { Map<String, FormFile> fileList = objForm.getFileList(); for(String str : fileList.keySet()) if((fileList.get(str)).getFileSize() > 0 && (fileList.get(str)).getFileSize() < BUFFER_SIZE) { String fileName = DIRECTORY +"/"+ fileList.get(str).getFileName(); try { this.fileStream( fileList.get(str).getInputStream(), fileName, fileList.get(str).getFileSize()); } catch (IOException ex) { System.out.println(ex.getMessage()); } } } /* * 使用org.apache.strtus.upload.FormFile实现文件的单一上传 */ private void singleUploadFile(IndexActionForm objForm) { if(objForm.getFile().getFileSize() == 0|| BUFFER_SIZE < objForm.getFile().getFileSize()) throw new RuntimeException("文件过大或不存在!!!"); String fileName = DIRECTORY +"/"+ objForm.getFile().getFileName(); try { this.fileStream( objForm.getFile().getInputStream(), fileName, objForm.getFile().getFileSize()); } catch (IOException ex) { System.out.println(ex.getMessage()); } } /* * copy 到本地目录 */ private void fileStream(InputStream strem, String fileName, int size) { byte[] buffer = new byte[size]; try { InputStream in = null; OutputStream out = null; try{ in = new BufferedInputStream(strem, size); out = new BufferedOutputStream(new FileOutputStream(fileName), size); while(in.read(buffer) > 0) out.write(buffer); }finally { if(null != in) in.close(); if(null != out){ out.flush(); out.close(); } } System.out.println("Uploading Success!!!"); } catch (IOException ex) { System.out.println(ex.getMessage()); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值