文件上传与下载————>struts

下载时设置前台的响应类型:response.setContentType("application/x-download");
os = response.getOutputStream();
is = new FileInputStream(new File(path));

上传时设置前台的相应类型:response.setContentType("text/html;charset=gb2312");
FileOutputStream fos = new FileOutputStream(tempFile + filePath + "\\" + fileName);
fos.write(fileItem.get());

乱码转换:

EncodeFilter类实现servlet包下的Filter接口
doFilter方法中:
request.setCharacterEncoding("UTF-8");    //将请求以UTF-8形式传输
chain.doFilter(request, response);    //将请求放行

action中:
UpLoadForm upLoadForm = (UpLoadForm)form;
FormFile photo = upLoadForm.getPhoto();    //FormFile是formBean中定义的文件类型

oracle函数:

nvl(a,b):       如果a不为则返回a,否则返回b

nvl(a,b,c):    如果a不为则返回b,否则返回c

decode(value,if1,then1,if2,then2,if3,then3,…,else)表示value等于if1时, 结果是then1。。。

select instr(“yuechaotianyuechao”,”ao”,-1,1)position from dual;(-1是开始位置,1是次数) — 17

substr(“abcde”,-6,5 )=null    -6是从右往左数第6个位置开始,5是要取得字符串长度

substr(“abcde”,-5,5 )= abcde       -6是从右往左数第6个位置开始,5是要取得字符串长度

mod(a,b):  对a和b取余

row_number() over(partition by … order by …)


UpLoadForm upLoadForm = (UpLoadForm)form;
FormFile photo = upLoadForm.getPhoto();
response.setContentType("text/html;charset=UTF-8");    //设置输出内容格式
String fileName = photo.getFileName();        
InputStream contentStream = photo.getInputStream();
String saveDir = this.getServlet().getServletContext().getRealPath("/");
File filePhoto = new File(saveDir,fileName);
FileOutputStream fos = new FileOutputStream(filePhoto );
/**
int len =0;
byte[] buf = new byte[1024];    //创建1024字节的byte数组
while((len = contentStream.read(buf)) != -1)    //如果读到内容
{
     fos.write(buf,0,len);    //将读到的下标从0到len长度的内容输出到文件输出流中
 }    
*/
fos.write(upLoadForm.getPhoto().getFileData());//代替上面几行
contentStream .close();    //关闭流

fos.close();    //关闭流





第一步:编写页面文件

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <%@includefile="/header.jsp"%>
    <title>struts上传文件</title>
  </head>
  <body>
   <h2>使用Struts上传文件</h2>
     <hr/>
    <form. action="<%=basePath%>strutsfileupload.do?method=upload" method="post"
           enctype="multipart/form-data">
       <table>
         <tr>
           <td>请选择要上传的文件</td>
           <td>
              <input type="file" name="filePath" size="20"/><br/>
           </td>
         </tr>
         <tr>
            <td>
              <input type="submit" value="上传"/>
            </td>
            <td>
              <a href="<%=basePath%>strutsfileupload.do?method=download&path=fileload/xxxx.txt">我要下载</a>
            </td>
         </tr>
        </table>
    </form>
  </body>
</html>
第二步:struts-config.xml文件,包含form-bean 和action的配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
 <data-sources />
 <form-beans >
      <form-bean name="fileUploadForm"
            type="com.xinglongjian.struts.fileupload.FileUploadForm" />
 </form-beans>
 <global-exceptions />
 <global-forwards>
  <forward name="error" path="/error/sysError.jsp"></forward>
 </global-forwards>
 <action-mappings>
  <action path="/strutsfileupload" parameter="method" name="fileUploadForm"
            type="com.xinglongjian.struts.fileupload.FileUploadAction" >
              <forward name="success" path="/struts/success.jsp"></forward>
        </action>
 </action-mappings>
</struts-config>

第三步:FileUploadForm.java

public class FileUploadForm. extends ActionForm
{
 private FormFile filePath; //类型为FormFile,变量filePath与页面的file名称一致。

 public FormFile getFilePath()
 {
  return filePath;
 }

 public void setFilePath(FormFile filePath)
 {
  this.filePath = filePath;
 }
 
}

第四步:FileUploadAction.java

public class FileUploadAction extends DispatchAction
{
 /**
  * 上传文件
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  * @throws Exception
  */
 public ActionForward upload(ActionMapping mapping, ActionForm. form, HttpServletRequest request, HttpServletResponse response)throws Exception
 {
  FileUploadForm. fileForm=(FileUploadForm)form;
  FormFile file=fileForm.getFilePath();
  String realPath=this.getServlet().getServletContext().getRealPath("/fileload");
  if(file==null)
   return mapping.findForward("error");
  String filename=file.getFileName();
  int size=file.getFileSize();
  if(size>1024*1024)
   return mapping.findForward("error");
  InputStream is=null;
  BufferedOutputStream bs=null;
  try
  {
   //get a inputstream object form. uploadFile
   is=file.getInputStream();
   bs=new BufferedOutputStream(new FileOutputStream(realPath+"/"+filename));
   byte[] buffer=new byte[20480];
   int count=0;
   while((count=is.read())!=-1)
    bs.write(buffer, 0, count);
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
  finally
  {
   bs.flush();
   bs.close();
   is.close();
  }
  
  return mapping.findForward("success");
 }
 /**
  * 下载文件
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  * @throws Exception
  */
 public ActionForward download(ActionMapping mapping, ActionForm. form, HttpServletRequest request, HttpServletResponse response)throws Exception
 {
  String path=request.getParameter("path");
  String realPath=this.getServlet().getServletContext().getRealPath("/"+path);
  
  File uploadFile=new File(realPath);
  InputStream is=new FileInputStream(uploadFile);
  OutputStream s=response.getOutputStream();
  
  BufferedInputStream bis=new BufferedInputStream(is);
  BufferedOutputStream bos=new BufferedOutputStream(os);
  //弹出下载对话框的代码
  response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(path,"utf-8"));
  int bytesRead=0;
  byte[] buffer=new byte[8192];
  while((bytesRead=bis.read(buffer, 0, 8192))!=-1)
   bos.write(buffer, 0, bytesRead);
  bos.close();
     is.close();
     bis.close();
     os.close();
  return null;
 }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值