com.mingsoft.basic.servlet.UploadServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.mingsoft.basic.servlet.UploadServlet.java

Source

/**
The MIT License (MIT) * Copyright (c) 2015 
    
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
    
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
    
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.mingsoft.basic.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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 com.mingsoft.util.FileUtil;
import com.mingsoft.util.StringUtil;

/**
 * servlet
 * @author QQ:78750478
 * @version 
 * ?100-000-000<br/>
 * 2012-03-15<br/>
 * ?<br/>
 */
@WebServlet(urlPatterns = "/upload")
public class UploadServlet extends BaseServlet {

    /**
     * ?post
     * @param req HttpServletRequest
     * @param res HttpServletResponse 
     * @throws ServletException ?
     * @throws IOException ?
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html;charset=utf-8");
        PrintWriter out = res.getWriter();
        String uploadPath = this.getServletContext().getRealPath(File.separator); // 
        String isRename = "";// ???? true:???
        String _tempPath = req.getServletContext().getRealPath(File.separator) + "temp";//
        FileUtil.createFolder(_tempPath);
        File tempPath = new File(_tempPath); // 

        int maxSize = 1000000; // ??,?? 1000000/1024=0.9M
        //String allowedFile = ".jpg,.gif,.png,.zip"; // ?
        String deniedFile = ".exe,.com,.cgi,.asp"; // ??

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        // ?????
        factory.setSizeThreshold(4096);
        // the location for saving data that is larger than getSizeThreshold()
        // ?SizeThreshold?
        factory.setRepository(tempPath);

        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum size before a FileUploadException will be thrown

        try {
            List fileItems = upload.parseRequest(req);

            Iterator iter = fileItems.iterator();

            // ????
            String regExp = ".+\\\\(.+)$";

            // 
            String[] errorType = deniedFile.split(",");
            Pattern p = Pattern.compile(regExp);
            String outPath = ""; //??
            while (iter.hasNext()) {

                FileItem item = (FileItem) iter.next();
                if (item.getFieldName().equals("uploadPath")) {
                    outPath += item.getString();
                    uploadPath += outPath;
                } else if (item.getFieldName().equals("isRename")) {
                    isRename = item.getString();
                } else if (item.getFieldName().equals("maxSize")) {
                    maxSize = Integer.parseInt(item.getString()) * 1048576;
                } else if (item.getFieldName().equals("allowedFile")) {
                    //               allowedFile = item.getString();
                } else if (item.getFieldName().equals("deniedFile")) {
                    deniedFile = item.getString();
                } else if (!item.isFormField()) { // ???
                    String name = item.getName();
                    long size = item.getSize();
                    if ((name == null || name.equals("")) && size == 0)
                        continue;
                    try {
                        // ?? 1000000/1024=0.9M
                        upload.setSizeMax(maxSize);

                        // ?
                        // ?
                        String fileName = System.currentTimeMillis() + name.substring(name.indexOf("."));
                        String savePath = uploadPath + File.separator;
                        FileUtil.createFolder(savePath);
                        // ???
                        if (StringUtil.isBlank(isRename) || Boolean.parseBoolean(isRename)) {
                            savePath += fileName;
                            outPath += fileName;
                        } else {
                            savePath += name;
                            outPath += name;
                        }
                        item.write(new File(savePath));
                        out.print(outPath.trim());
                        logger.debug("upload file ok return path " + outPath);
                        out.flush();
                        out.close();
                    } catch (Exception e) {
                        this.logger.debug(e);
                    }

                }
            }
        } catch (FileUploadException e) {
            this.logger.debug(e);
        }
    }

    //   /**
    //    * ?get
    //    * @param request HttpServletRequest
    //    * @param response HttpServletResponse 
    //    * @throws ServletException Servlet?
    //    * @throws IOException IO?
    //    */
    //   @Override
    //   protected void doGet(HttpServletRequest request, HttpServletResponse response)
    //         throws ServletException, IOException {
    //      String uploadPath = request.getParameter("uploadPath"); // 
    //      String fileSize = request.getParameter("fileSize"); // ?
    //      String fileType = request.getParameter("fileType"); // 
    //      String deniedFileType = request.getParameter("deniedFileType"); // ??
    //   }
}