java实现文件的上传下载

package upload;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
 
/**
  * 上传文件
  */
import java.io.PrintWriter;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
import exception.FileSizeException;
import exception.FileTypeException;
 
import util.WebUtil;
 
public class FileUploadServlet extends HttpServlet {
     
     
 
     public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         
     }
 
     
     public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         
         try {
             //通知浏览器以UTF-8的方式来解码
             request.setCharacterEncoding( "UTF-8" );
             //创建上传文件的工厂
             DiskFileItemFactory factory = new DiskFileItemFactory();
             //设置上传文件的临时缓存区为100k
             factory.setSizeThreshold( 100 * 1024 );
             //定位临时目录的路径,这里的/表示当前Web应用的根目录
             String tempPath = this .getServletContext().getRealPath( "/WEB-INF/temp" );
             //设置上传文件超过100K的临时目录存放点
             factory.setRepository( new File(tempPath));
             //创建上传文件对象(核心)
             ServletFileUpload fileUpload = new ServletFileUpload(factory);
             //判断客户端是否已RCF协议的方式上传
             if (fileUpload.isMultipartContent(request)){
                 //解析request对象中的表单字段
                 List<FileItem> fileItemList = fileUpload.parseRequest(request);
                 //迭代
                 for (FileItem fileItem : fileItemList){
                     //如果是普通字段
                     if (fileItem.isFormField()){
                         String fileName = fileItem.getFieldName();
                         String fileNameValue = fileItem.getString( "UTF-8" );
                         //显示
                         System.out.println(fileName + ":" + fileNameValue);
                     } else if (!fileItem.isFormField()){
                         //获取上传文件的名字
                         String filename = fileItem.getName();
                         //获得UuidFileName
                         String uuidFileName = WebUtil.makeUuidFileName(filename);
                         System.out.println(uuidFileName);
                         //定位上传文件的存放的目录
                         String uploadPath = this .getServletContext().getRealPath( "/WEB-INF/upload" );
                         //获取上传文件存放的子目录
                         String subUploadPath = WebUtil.subUploadPath(uploadPath,uuidFileName);
                         //获取上传文件的大小
                         long size = fileItem.getSize();
                         //如果上传文件超过200K
                         if (size> 200 * 1024 ){
                             //人工抛出异常
                             throw new FileSizeException();
                         }
                         //获取上传文件的类型
                         String contentType = fileItem.getContentType();
                         //如果上传的文件类型不是JPG格式
                         if (! "image/jpeg" .equals(contentType)){
                             //人工抛出异常
                             throw new FileTypeException();
                         }
                         
                         
                         
                         
                         //调用工具类的方法writeToFiel
                         WebUtil.writeToFile(fileItem, subUploadPath, uuidFileName);
                         
                         /*//获取上传文件输入流
                         InputStream is = fileItem.getInputStream();
                         //定位文件输出流
                         OutputStream os = new FileOutputStream(new File(uploadPath + "/" + name));
                         //将上传文件写入指定的目录下
                         byte[] buf = new byte[2048];
                         int len = 0;
                         while((len = is.read(buf))>0){
                             os.write(buf,0,len);
                         }
                         os.close();
                         is.close();
                         */
                         //把临时文件删除
                         fileItem.delete();
                     }
                 }
                 request.setAttribute( "message" , "<font style = 'font-size:111ps;color:red'>上传成功</font>" );
                 request.getRequestDispatcher( "/WEB-INF/message.jsp" ).forward(request, response);
             } else {
                 request.setAttribute( "message" , "<font style = 'font-size:111px;color:red'>上传文件必须采用RFC协议指定的格式</font>" );
                 request.getRequestDispatcher( "/WEB-INF/message.jsp" ).forward(request, response);
             }
         }
         //上传文件的大小不能超过200K
         catch (FileSizeException e) {          
             e.printStackTrace();
             request.setAttribute( "message" , "<font style = 'font-size:111ps;color:red'>上传文件失败!上传文件不能超过200K</font>" );
             request.getRequestDispatcher( "/WEB-INF/message.jsp" ).forward(request, response);           
         }
         //上传文件必须为图片类型
         catch (FileTypeException e) {          
             e.printStackTrace();
             request.setAttribute( "message" , "<font style = 'font-size:111ps;color:red'>上传文件失败!上传文件必须是图片类型的</font>" );
             request.getRequestDispatcher( "/WEB-INF/message.jsp" ).forward(request, response);           
         }
         catch (Exception e) {          
             e.printStackTrace();
             request.setAttribute( "message" , "<font style = 'font-size:111ps;color:red'>解析上传表单出错</font>" );
             request.getRequestDispatcher( "/WEB-INF/message.jsp" ).forward(request, response);
         
         }
     }
 
}













<%@ page language= "java" import = "java.util.*" pageEncoding= "UTF-8" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >
<html>
   <head>
 
     
     <title>My JSP 'list.jsp' starting page</title>
     
     <meta http-equiv= "pragma" content= "no-cache" >
     <meta http-equiv= "cache-control" content= "no-cache" >
     <meta http-equiv= "expires" content= "0" >   
     <meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" >
     <meta http-equiv= "description" content= "This is my page" >
 
   </head>
   
   <body>
     <table border = "2" align = "center" width = "40%" >
         <tr>
             <th>文件</th>
             <th>操作</th>
         </tr>
         <c:forEach var = "entry" items = "${requestScope.MAP}" >
             <tr>
                 <td>${entry.value}</td>
                 <td> 
                     <c:url var = "myURL" value = "/fileDownload" >
                         <c:param name = "uuidFileName" value = "${entry.key}" />
                     </c:url>
                     <a style = "text-decoration:none"
                         href = "${myURL}" >下载</a>
                 </td>
             </tr>
         </c:forEach>
     </table>
   </body>
</html>


转载于:https://my.oschina.net/JohnXO/blog/684754

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值