FileUpLoad

Posted 来自IT国的猴子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FileUpLoad相关的知识,希望对你有一定的参考价值。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.toher.DataImport;

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.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.coobird.thumbnailator.Thumbnails;
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 org.apache.commons.lang.StringUtils;

/**
 *
 * @author Toher
 */
@WebServlet(name = "FileUpLoad", urlPatterns = {"/FileUpLoad"})
public class FileUpLoad extends HttpServlet {

    private final String uploadLoation = "uploadfile"; //保存的文件夹名称

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("utf-8");  //设置编码

        //获取用户UserNo作用于文件夹创建
        String UserNo = "";
        if (StringUtils.isBlank(UserNo)) {
            UserNo = request.getParameter("userNo");
        }
        //设置项目访问路径
        String ContextPath = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + ContextPath + "/";
        
        PrintWriter Printout = response.getWriter();
        //获得磁盘文件条目工厂  
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //获取文件需要上传到的路径
        String path = request.getSession().getServletContext().getRealPath("/") + uploadLoation + File.separator + UserNo;
       
        File pathFile = new File(path);
        //文件以及路径是否存在
        if (!pathFile.exists()) {
            //文件夹 
            pathFile.mkdirs();
        }
        //创建一个文件上传处理器
        factory.setRepository(new File(path));
        //设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室  
        factory.setSizeThreshold(1024 * 1024);
        //高水平的API文件上传处理  
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            //可以上传多个文件,解析表单中的每一个表单项,封装成FileItem对象,以List方式返回,表单("enctype="multipart/form-data"")
            List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
            String newFileName = "";
            for (FileItem item : list) {
                //获取表单的属性名字  
                String name = item.getFieldName();
                //如果获取的 表单信息是普通的 文本 信息  
                if (item.isFormField()) {
                    //获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的  
                    String value = item.getString();
                    request.setAttribute(name, value);
                } else {
                    //获取路径名  
                    String value = item.getName();
                    String fileExt = value.substring(value.lastIndexOf(".") + 1);
                    //设置新的文件名,这里我们采用日期格式,当然我们还可以使用UUID
                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                    newFileName = df.format(new Date()) + (int) (Math.random() * 1000) + "." + fileExt;

                    String uploadFolder = path + File.separator + newFileName;
                    File file = new File(uploadFolder);
//        到这一步,就开始把request中获取到的文件写入到我预先处理好的路径地址加名字的文件中,write
                    item.write(file);
                }
                /* 上传成功后,进行数据返回!*/
            }
            Printout.println("{\"code\":\"success\",\"msg\":\"/"+ uploadLoation +"/"+UserNo+"/"+ newFileName + "\"}");

        } catch (Exception e) {
            e.printStackTrace();
            Printout.println("{\"code\":\"error\",\"msg\":\"\"}");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

 

以上是关于FileUpLoad的主要内容,如果未能解决你的问题,请参考以下文章

从 CompleteWizardStep 获取对象 (FileUpload)

FileUpload:使用 JS 获取文件名不起作用

C# 自定义FileUpload控件

ASP.NET利用.FileUpload上传图片并将图片名称保存到数据库,我要具体的代码

FileUpload上传总结

GWT FileUpload - 通过客户端代码设置响应 Content-Type