javaweb文件上传和下载实现

在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现。

一、实现文件的上传

       1.1 前端页面

html代码如下

<input class="inputFile" type="file" name=""  value="">

           js代码如下

        // 监控上传后的事件
		$(".inputFile").live('change',function(){
			var source = $(this);
			var item = source[0].files[0]; 
            var formData = new FormData();
            formData.append("uploadItem",item);
            var xhr = new XMLHttpRequest();
            xhr.open("post","/servlet/UploadFlieServlet?function=SetPortfolioImage");
            //注册相关事件回调处理函数
            xhr.onload = function(e) { 
              if(this.status == 200||this.status == 304){
            	  var responseText =  eval("("+this.responseText+")");
              }
            };
            xhr.send(formData);
		});

1.2处理文件上传的Servlet

package root;

import java.io.File;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.thinkive.base.util.DateHelper;
import com.thinkive.base.util.FileHelper;
import com.thinkive.base.util.StringHelper;
import com.thinkive.web.base.ActionResult;
import com.thinkive.web.base.BaseAction;
import com.thinkive.web.system.Application;


public class UploadFlieServlet extends BaseAction
{
    private Logger       logger   = Logger.getLogger(UploadFlieServlet.class);
    
    private String       fileName = "";
    
    private String       fileUrl  = "";
    
    private File         savefile = null;
    
    public ActionResult doSetPortfolioImage()
    {
        try
        {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(getRequest());
            
            String uploadPath = getUploadPath();
            logger.info("uploadPath===="+uploadPath);
            uploadPath = FileHelper.normalize(uploadPath);
            if ( !FileHelper.isDirectory(uploadPath) )
            {
                FileHelper.createDirectory(uploadPath);
            }
            for (FileItem item : items)
            {
                if ( !item.isFormField() )
                {
                    // 得到上传文件的文件名
                    fileName = item.getName();
                    if ( fileName == null && fileName.trim().length() == 0 )
                    {
                        continue;
                    }
                    // 得到上传文件的扩展名
                    String fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
                    String newFileName = String.valueOf(DateHelper.formatDate(new Date(), "yyyyMMdd")
                            + System.currentTimeMillis());
                    if ( !StringHelper.isEmpty(fileExt) )
                    {
                        newFileName = newFileName + fileExt;
                    }
                    
                    fileUrl = uploadPath + newFileName;
                    savefile = new File(fileUrl);
                    item.write(savefile);
                    fileUrl = getUploadUrlPath() + newFileName;
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        JSONArray jsonArr = new JSONArray();
        JSONObject jsonObj = new JSONObject();
        PrintWriter out = null;
        try
        {
            out = getResponse().getWriter();
            jsonObj.put("file_path", fileUrl);
            jsonObj.put("file_name", fileName);
            jsonArr.add(jsonObj);
            out.print(jsonArr.toString());
            out.flush();
            out.close();
            logger.info("上传完成");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
        return null;
        
    }
    
    private String getUploadPath()
    {
        String datePath = DateHelper.formatDate(new Date(), "yyyyMMdd");
        return Application.getRootPath() + "/upload/delivery/" + datePath + "/";
    }
    
    private String getUploadUrlPath()
    {
        String datePath = DateHelper.formatDate(new Date(), "yyyyMMdd");
        return "/upload/delivery/" + datePath + "/";
    }
}

二、实现文件的下载

2.1下载文件的Servlet

 OutputStream out = null;
        BufferedInputStream in = null;
        try
        {
            // 得到上传文件的扩展名
            String file_type = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
            if ( "gif".equalsIgnoreCase(file_type) || "jpg".equalsIgnoreCase(file_type)
                    || "jpeg".equalsIgnoreCase(file_type) || "png".equalsIgnoreCase(file_type))
            {
                response.setContentType("application/image");
                response.setHeader("Content-Disposition", WAY + "; filename=\"" + URLEncoder.encode(fileName,"utf-8") + "\"");
            }
            else 
            {
                response.setContentType("application/" + file_type);
                response.setHeader("Content-Disposition", WAY + "; filename=\"" + URLEncoder.encode(fileName,"utf-8") + "\"");
            }
            URL url = new URL(path);
            out = response.getOutputStream();
            in = new BufferedInputStream(url.openStream());
            
            int line;
            while ((line = in.read()) != -1)
            {
                out.write(line);
            }
            out.close();
            in.close();
        }
        catch (Exception ex)
        {
            logger.error("", ex);
        }
        finally
        {
            if ( out != null )
            {
                try
                {
                    out.close();
                }
                catch (IOException e)
                {
                    logger.error("", e);
                }
            }
            
            if ( in != null )
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    logger.error("", e);
                }
            }
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值