struts实现图片上传

struts实现图片上传

文件上传:
三种上传方案
1、上传到tomcat服务器
2、上传到指定文件目录,添加服务器与真实目录的映射关系,从而解耦上传文件与tomcat的关系
文件服务器
3、在数据库表中建立二进制字段,将图片存储到数据库
课程目标:图片上传以及页面展示
思路:
1、完成功能
今天我们用第2个上传方案进行图片上传
下面我们来用代码实现功能
首先我们写一个控制器
这个控制器的功能就是得定义文件的属性以及图片的路径

package com.xy.crud.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 java.util.List;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ModelDriven;
import com.xy.crud.dao.ClazzDao;
import com.xy.crud.entity.Clazz;
import com.xy.crud.util.BaseAction;
import com.xy.crud.util.PageBean;

public class ClazzAction extends BaseAction implements ModelDriven<Clazz> {

	private ClazzDao clzDao = new ClazzDao();
	private Clazz clz = new Clazz();
	
	private File file;
	private String fileContentType;
	private String fileFileName;
	
	
	public File getFile() {
		return file;
	}

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

	public String getFileContentType() {
		return fileContentType;
	}

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

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	
	
	
	/**
	 * 上传图片
	 * @return
	 */
	public String Upload() {
		try {
//			注意:在Linux下没有E盘的,Linux下只有哦一个盘符,那么意味着,当打包到Linux服务器的时候需要改动代码
//			这个时候通常是这么解决的,将targetPath对应目录串,配置到资源文件中,通过Properties类进行动态读取
//			那么当需要将项目发布到Linux服务器的时候,只需要改变xxx.properties文件中的targetPath=/xxx/img/
			
//			实际图片存储的位置
			String targetDir="F:/img";
//			存到数据中的地址
			String serverPath="/uploads";
//			FileUtils.copyFile(file, new File(targetDir+"/"+fileFileName));
			copyBufFile(file, new File(targetDir+"/"+fileFileName));
//			注意:数据库存放的是网络请求地址,而不是本地储存地址
			clz.setPic(serverPath+"/"+fileFileName);
			this.clzDao.edit(clz);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "toList";
	}
	
	/**
	 * FileUtils.copyFile的底层,并且通过缓冲区进行了增强
	 * @param source
	 * @param target
	 * @throws FileNotFoundException
	 */
	public void copyBufFile(File source,File target) throws FileNotFoundException {
		BufferedInputStream in=new BufferedInputStream(new FileInputStream(source));
		BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(target));
		byte[] bbuf=new byte[1024];
		int len=0;
			try {
				while((len = in.read(bbuf))!=-1) {
						out.write(bbuf,0,len);
					}
				in.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			} 
	}
	
	/**
	 * 跳转文件上传页面
	 * @return
	 */
	public String preUpload() {
		if(clz.getCid()!=0) {
			Clazz z;
			try {
				z = this.clzDao.list(clz, null).get(0);
				request.setAttribute("clz", z);
			} catch (IllegalArgumentException | IllegalAccessException | InstantiationException | SQLException e) {
				e.printStackTrace();
			}
		}
		return "toUpload";
	}
	
	
	

	/**
	 * 查所有
	 * 
	 * @return
	 * @throws SQLException 
	 * @throws InstantiationException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	public String list() throws IllegalArgumentException, IllegalAccessException, InstantiationException, SQLException {
		PageBean pageBean = new PageBean();
		pageBean.setRequest(request);
		List<Clazz> list = this.clzDao.list(clz, pageBean);
		request.setAttribute("clzList", list);
		request.setAttribute("pageBean", pageBean);
		return "list";
	}

	/**
	 * 跳转新增修改页面的公用方法
	 * 
	 * @return
	 * @throws SQLException 
	 * @throws InstantiationException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	public String preSave() throws IllegalArgumentException, IllegalAccessException, InstantiationException, SQLException {
		if(clz.getCid()!=0) {
			Clazz z = this.clzDao.list(clz, null).get(0);
			request.setAttribute("clz", z);
		}
		return "preSave";
	}

	public String edit() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		this.clzDao.edit(clz);
		return "toList";
	}
	
	/**
	 * 新增方法
	 * @return
	 */
	public String add() {
		try {
			result=this.clzDao.add(clz);
		} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
				| SQLException e) {
			e.printStackTrace();
		}
		return "toList";
	}

	public String del() {
		try {
			this.clzDao.del(clz);
		} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
				| SQLException e) {
			e.printStackTrace();
		}
		return "toList";
	}

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

然后我们在写一个上传图片的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>Insert title here</title>
</head>
<body>

	<form action="${pageContext.request.contextPath}/sy/clz_Upload.action" method="post" enctype="multipart/form-data">
		<input type="hidden" name="cid" value="${clz.cid }" /><br/>
		<input type="hidden" name="cname" value="${clz.name }" /><br/>
		<input type="hidden" name="cteacher" value="${clz.teacher }" /><br/>
		<input type="file" name="file" />
		<input type="submit" />
	</form>

</body>
</html>

写完这个还需要配置一下xml

<?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE struts PUBLIC
      "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
     "http://struts.apache.org/dtds/struts-2.5.dtd">
 <struts>
     <package name="sy" extends="base" namespace="/sy"> 
         <action name="/clz_*" class="com.web.ClazzAction" method="{1}">
           <result name="list">/clzList.jsp</result>
             <result name="preSave">/clzEdit.jsp</result>
            <result name="toList" type="redirectAction">/clz_list</result>
          <result name="toUpload">/upload.jsp</result>
         </action>
     </package>
 </struts>

还有一个显示界面:

<c:forEach items="${clzList }" var="c">
             <tr>
                 <td>${c.cid }</td>
                <td>${c.cname }</td>
                <td>${c.cteacher }</td>
                 <td>
                 <img alt="" style="width: 60px;height: 60px" src="${pageContext.request.contextPath }${c.pic }">
                 </td>
                <td>
                    <a href="${pageContext.request.contextPath }/sy/clz_preSave.action?cid=${c.cid }">修改</a>&nbsp;&nbsp;
                   <a href="${pageContext.request.contextPath }/sy/clz_del.action?cid=${c.cid }">删除</a>&nbsp;&nbsp;
                    <a href="${pageContext.request.contextPath }/sy/clz_preUpload.action?cid=${c.cid }">上传图片</a>&nbsp;&nbsp;
                 </td>
             </tr>
      </c:forEach>

然后就完成了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/* * 使用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、付费专栏及课程。

余额充值