struts实现简单的文件上传与下载

最近做个个上传下载的应用,将代码共享出来,一起学习
//其中<span style="font-family: Arial, Helvetica, sans-serif;">private FormFile myfile;表示struts中,jsp页面传过来的文件,ActionForm表单</span>

<pre name="code" class="java">import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;


public class UserForm extends ActionForm {

	private String name;
	private String xuehao;
	private String homeworktimes;
	private FormFile myfile;<span style="font-family: Arial, Helvetica, sans-serif;">//其中</span><span style="font-family: Arial, Helvetica, sans-serif;">private FormFile myfile;表示struts中,jsp页面传过来的文件</span>

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getXuehao() {
		return xuehao;
	}
	public void setXuehao(String xuehao) {
		this.xuehao = xuehao;
	}
	public FormFile getMyfile() {
		return myfile;
	}
	public void setMyfile(FormFile myfile) {
		this.myfile = myfile;
	}
	public String getHomeworktimes() {
		return homeworktimes;
	}
	public void setHomeworktimes(String homeworktimes) {
		this.homeworktimes = homeworktimes;
	}
}


 
 
//下载文件
import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.edu.ujs.Bean.FileListBean;
import cn.edu.ujs.service.DownService;

public class DownAction extends Action {
	
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		// TODO Auto-generated method stub
		String newfilename=null;
		newfilename=(String) request.getParameter("newfilename");
		System.out.println(newfilename);
		if(newfilename==null){
			return mapping.findForward("fail");
		}
		DownService ds=new DownService();
		FileListBean flbean=ds.getDownFile(newfilename);
		
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("Content-Disposition", "attachment;fileName="+flbean.getOldfilename());
		
		String filePath=this.getServlet().getServletContext().getRealPath("/files");
		String fileAllPath=filePath+flbean.getNewfilename();
		FileInputStream fis=null;
		OutputStream os=null;
		byte[] buffer=new byte[1024];
		int len;
		try{
			fis=new FileInputStream(fileAllPath);
			os=response.getOutputStream();
			while((len=fis.read(buffer))>0){
				os.write(buffer, 0, len);
			}
			os.flush();
		
		}catch(Exception e){
			e.printStackTrace();
		}finally{
		
			if(os!=null){
				os.close();
			}
			if(fis!=null){
				fis.close();
			}
			
		}
	
			return null;//return null;解决response.OutouStream()和response.Writer();不能同时存在是问题
		}
}
 
 

上传文件

package cn.edu.ujs.action;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import cn.edu.ujs.Bean.FileListBean;
import cn.edu.ujs.form.UserForm;
import cn.edu.ujs.service.UpService;
import cn.edu.ujs.utils.MyTools;
public class UpAction extends Action {

public ActionForward execute(ActionMapping mapping, ActionForm form,
		HttpServletRequest request, HttpServletResponse response)
		throws Exception {
	ActionForward forward=new ActionForward();
	UserForm userForm=(UserForm) form;
	System.out.println("名称:"+userForm.getName()+"  "+userForm.getXuehao()+"  "+userForm.getMyfile()+"  "+userForm.getHomeworktimes());
	UpService ups=new UpService();
	//System.out.println("文件大小为:"+userForm.getMyfile().getFileSize());
	if(userForm.getXuehao().isEmpty()||userForm.getName().isEmpty()||userForm.getMyfile().getFileSize()==0){
		request.setAttribute("err", "请输入完整信息");
		forward=mapping.findForward("fail");
		return forward;
	}
	if(!ups.isUser_Exist(userForm.getXuehao(),userForm.getName())){
		request.setAttribute("err", "您输入的学号不存在,或学号姓名不匹配");
		forward=mapping.findForward("fail");
		return forward;
	}
	if(ups.isFile_Exist(userForm.getXuehao(),userForm.getHomeworktimes())){
		request.setAttribute("err", "您的文件已上传,请勿多次提交!");
		forward=mapping.findForward("fail");
		return forward;
	}
	FormFile formFile=userForm.getMyfile();
	String oldfilename=formFile.getFileName();
	String filepath=this.getServlet().getServletContext().getRealPath("/files");
	String newfilename=MyTools.getNewFileName(oldfilename);
	String fileAllPath=filepath+newfilename;
	System.out.println(filepath);
	InputStream is=null;
	OutputStream os=new FileOutputStream(fileAllPath);
	try {
		is=formFile.getInputStream();
		int len=0;
		byte[] bytes=new byte[1024];
		while((len=is.read(bytes))>0){
			os.write(bytes, 0, len);
		}

		FileListBean flbean=new FileListBean();
		flbean.setName(userForm.getName());
		flbean.setXuehao(userForm.getXuehao());
		flbean.setOldfilename(oldfilename);
		flbean.setNewfilename(newfilename);
		flbean.setHomeworktimes(userForm.getHomeworktimes());
		flbean.setState(1);
		ups.addFile(flbean);
		forward=mapping.findForward("ok");
		
		
	} catch (Exception e) {
		// TODO: handle exception
		forward=mapping.findForward("fail");
		e.printStackTrace();
	}finally{
		is.close();
		os.close();
	}
	return forward;
	
}
	
}




//UUID的方式获取随机文件的名字


import java.util.UUID;


public class MyTools {


	public static String getNewFileName(String filename){
		String newFileName=null;
		if(filename!=null&&!filename.equals("")){
			int beginIndex=filename.lastIndexOf(".");
			newFileName=UUID.randomUUID().toString()+filename.substring(beginIndex, filename.length());
		}
		return newFileName;
		
	}
}

//DBHelper数据库工具

import java.sql.*;

import javax.sql.*;
import javax.naming.*;

	public class DBHelper {  
	    public static final String url = "jdbc:mysql://127.0.0.1/HomeWork?useUnicode=true&characterEncoding=UTF-8";  
	    public static final String name = "com.mysql.jdbc.Driver";  
	    public static final String user = "root";  
	    public static final String password = "wutongyu";  
	  
	    public static Connection conn = null;  
	    
	  
	    public static Connection getConn() {  
	        try {  
	            Class.forName(name);//指定连接类型  
	            conn = DriverManager.getConnection(url, user, password);//获取连接  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }
	        return conn;
	    }  
	    public static void main(String[] args){
	    	System.out.println(getConn());
	    }
	  
	}  

JSP页面中  <input type="file" name="myfile" value="上传"/><br>代表文件
<tr>
                                <th>文件</th>
                                <td width="245">
                                    <input type="file" name="myfile" value="上传"/><br>
	
                                </td>
                                <td>
                                </td>
                            </tr>

你可能感兴趣的:(struts实现简单的文件上传与下载)