日期:2014-05-16  浏览次数:20443 次

struts上传图片到数据库

??? 这几天研究了一个struts上传到服务器,然后服务器转存到数据库的例子。直接上代码吧……

??? 要值得注意的是,文件上传到服务器后,其文件名和文件类型会被更改,保持不变的只有文件的文件流……

??? 这是action的代码:

package com.test.action;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.test.dao.UploadDAO;

public class UploadAction extends ActionSupport{
	
	private static final long serialVersionUID = -3541943466145372393L;
	
	private static final String LOGIN = "login";
	
	private List<File> files;

	public List<File> getFile() {
		return files;
	}

	public void setFile(List<File> file) {
		this.files = file;
	}
	
	public String execute() throws Exception{
		for (File file : files) {
			saveFile(file);
		}
		return "success";
	}
	
	private void saveFile(File file) throws IOException, ClassNotFoundException, SQLException{
		UploadDAO dao = new UploadDAO();
		dao.insertDB(file);
	}
	
	
	public String login(){
		return LOGIN;
	}
}

??? dao层的代码:

package com.test.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.test.util.DBConnection;

public class UploadDAO {
	public boolean insertDB(File file) throws ClassNotFoundException, SQLException, IOException{
		Connection conn = DBConnection.getConnection();
		String sql = "insert into imgtest(image) values(?)";
		InputStream stream = new FileInputStream(file);
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setBinaryStream(1, stream, stream.available());
		boolean result = ps.execute();
		return result;
	}
}
?

?? struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<!-- Action所在包定义 -->
	<constant name= "struts.multipart.maxSize" value="5242880" />
	<package name="fileupload" extends="struts-default" namespace="/">
		
		<action name="upload" class="com.test.action.UploadAction">
			<result name="login">/upload-input.jsp</result>
			<result name="success">/upload-result.jsp</result>
			<!-- 显示配置文件上传拦截器 -->
			<interceptor-ref name="fileUpload">
				<!--指定特定类型的上传文件 -->
				<param name="allowedTypes">image/gif,image/jpeg,image/pjpeg,text/xml,application/vnd.ms-excel</param>
			</interceptor-ref>
			<interceptor-ref name="defaultStack" />
		</action>

	</package>

</struts>