现在的位置: 首页 > 综合 > 正文

commons-fileupload-1.2.2实现java上传下载

2013年11月23日 ⁄ 综合 ⁄ 共 5079字 ⁄ 字号 评论关闭

package com.xp.file.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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 com.xp.file.bean.Files;
import com.xp.file.business.FilesService;
import com.xp.space.bean.AbstractCustomer;
import com.xp.space.bean.Customer;

public class SourceUploadAction extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        AbstractCustomer user = (Customer) session.getAttribute("user");
        // 文件名
        String value = "";
        if (user == null) {// 如果用户未登陆
            System.out.println(user);
            session.setAttribute("login", false);
            // 跳转到登陆页面
            request.getRequestDispatcher("sourcepage.jsp").forward(request,
                    response);
        } else {// 如果用户已登陆
            session.setAttribute("login", true);
            FilesService fs = new FilesService();

            Files file = new Files();

            // 获取用户名
            String userName = user.getName();
            // 获取用户ID
            int userId = user.getCustomerId();

            file.setOwner(userName);
            file.setOwnerId(userId);
            file.setDate(new Date());
            file.setPassedCheck(1);

            /* 文件处理正式开始 */

            // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
            DiskFileItemFactory dfif = new DiskFileItemFactory();
            dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘

            // 用以上工厂实例化上传组件
            ServletFileUpload sfu = new ServletFileUpload(dfif);
            // sfu.setHeaderEncoding("UTF-8");

            List fileList = null;
            try {

                // 文件存放真正位置
                String uploadRealPath = request.getSession()
                        .getServletContext().getRealPath("/")
                        + "upload//";
                File UploadRealPath = new File(uploadRealPath);
                UploadRealPath.mkdirs();

                // 文件存放URL位置
                String uploadURLPath = request.getScheme() + "://"
                        + request.getServerName() + ":"
                        + request.getServerPort() + request.getContextPath()
                        + "/upload/";

                fileList = sfu.parseRequest(request);

                // 从request得到 所有 上传域的列表
                Iterator it = fileList.iterator();

                // URL地址,下载链接

                while (it.hasNext()) {
                    // fileItem共有四项sourcetitle,sourceartical,sourcefile,sourcepostsubmit
                    FileItem fi = (FileItem) it.next();
                    // 字段名
                    String fieldName = fi.getFieldName();
                    if (fi.isFormField()) {
                        // String fieldName = fi.getFieldName();
                        value = new String(fi.getString()// 上传资源  可能会导致乱码
                                .getBytes("ISO-8859-1"), "UTF-8");
                    } else if (!fi.isFormField()) {
                        // 文件名
                        value = fi.getName();
                        value = value.substring((value.lastIndexOf("//") + 1)).replace(" ", "_");
                        InputStream is = fi.getInputStream();
                        OutputStream os = new FileOutputStream(UploadRealPath
                                .getPath()
                                + "/" + value);
                        byte[] buffer = new byte[1024];
                        int read = 0;
                        while ((read = is.read(buffer, 0, 1024)) != -1) {
                            os.write(buffer, 0, read);
                        }
                        session.setAttribute("filename", value);
                    }
                    if (fieldName.equalsIgnoreCase("sourcetitle")) {
                        file.setTitle(value);
                    } else if (fieldName.equalsIgnoreCase("sourceartical")) {
                        file.setDesciption(value);
                    } else if (fieldName.equalsIgnoreCase("sourcefile")) {
                        file.setFileUploadName(value);
                        file.setFileSaveName(uploadRealPath+value);
                        file.setFileURLPath(uploadURLPath + value);
                    } else {
                        System.out.println("something with upload");
                    }
                }

                // 上传列表都存到file
                if (fs.saveFilesToPersist(file)) {
                    System.out.println("上传成功");
                } else {
                    throw new SQLException("不能保存到数据库");
                }

            } catch (FileUploadException e) {// 处理文件尺寸过大异常
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            /* 文件处理非正式结束 */

            request.getRequestDispatcher("uploadsuccessfully.jsp").forward(
                    request, response);
        }
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}

抱歉!评论已关闭.