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>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elabor
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值