文件上传

package com.oracle.upload;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.oracle.domain.ResponseUpload;
import com.oracle.domain.UploadBean;
import com.oracle.domain.UserInfo;
import com.oracle.service.UploadService;
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.io.FileUtils;

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 java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Description TODO
 * @ClassName UploadServlet
 * @Author YHY
 * @Date 2019/11/11 11:31
 * @Version V1.0
 */
@WebServlet(value = "/UploadServlet")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /* 处理响应乱码问题:字节流需getBytes("UTF-8") */
        /*response.setContentType("text/html;charset=UTF-8");*/
        /* 处理post请求乱码问题 */
        request.setCharacterEncoding("UTF-8");

        String fileName = ""; //文件名*/
        String href = "";/*服务器存储路径*/
        String loaclhost_file_name = "";
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userinfo");
        String upload_those = userInfo.getUid();
        String access_url = "";/*用户访问的相对路径*/

        /*用于返回数据*/
        Map map = new HashMap();

        boolean flag = ServletFileUpload.isMultipartContent(request);
        if (!flag) {
            request.setAttribute("msg", "表单的enctype属性不正确");
            request.getRequestDispatcher("jsp/upload.jsp").forward(request, response);
            return;
        }

        /*缓冲字节输出流*/
        BufferedOutputStream bos = null;
        /*缓冲字节输入流*/
        BufferedInputStream bis = null;

        /*1、创建磁盘文件工程*/
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        /*设置文件上传过程中缓冲区的大小*/
        diskFileItemFactory.setSizeThreshold(3);
        /*设置文件上传过程中超出缓冲区所产生的临时文件路径*/
        diskFileItemFactory.setRepository(new File("D://temporary"));
        /*2、创建一个核心解析类*/
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        /*解决中文乱码问题*/
        servletFileUpload.setHeaderEncoding("UTF-8");

        /*3、利用核心类解析request,解析后得到多个部分。返回list集合。list集合中装的值每个部分内容(FileItem文件项)。*/
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);

            /*4、遍历list集合,会得到代表每个部分的文件上传项的对象。根据文件项判断是否是文件上传项。*/
            for (FileItem f : fileItems) {
                /*判断这个文件项是普通项还是文件上传项*/
                if (f.isFormField()) {
                    /*普通项:*/
                    /*接收普通项的值,不能用request.getParameter()*/
                    /*获取普通项的key*/
                    String name = f.getFieldName();
                    /*接收普通项的值*/
                    String string = f.getString();
                    System.out.println(name + ":" + string);
                    if (name.equals("href")) {
                        href = string;
                    }
                    if (name.equals("access_url")) {
                        access_url = string;
                    }
                }
            }
            /*文件上传项*/
            for (FileItem file : fileItems) {
                if (!file.isFormField()) {
                    /*文件上传项*/
                    /*获取文件名*/
                    loaclhost_file_name = file.getName();
                    fileName = loaclhost_file_name;
                    int index = 0;
                    if ((index = fileName.lastIndexOf("\\")) != -1) {
                        loaclhost_file_name = loaclhost_file_name.substring(index + 1);
                    }
                    loaclhost_file_name = UploadServlet.randomFileNanm(loaclhost_file_name);
                    /*往request域中存储文件名*/
                    request.setAttribute("randomFileName", loaclhost_file_name.getBytes());
                    /*获取数据源*/
                    bis = new BufferedInputStream(file.getInputStream());

                    /*服务器存储路径*/
                    href = href + loaclhost_file_name;
                    /*用户访问的相对路径*/
                    access_url = access_url + loaclhost_file_name;

                    /*明确数据源*/
                    bos = new BufferedOutputStream(new FileOutputStream(href));
                    byte[] bytes = new byte[1024];
                    int line = 0;
                    while ((line = bis.read(bytes)) != -1) {
                        bos.write(bytes, 0, line);
                    }
                    if (bos != null && bis != null) {
                        /*释放资源*/
                        bos.close();
                        bis.close();
                    }
                    /*5、删除临时文件*/
                    file.delete();

                    FileUtils.copyFile(new File("D:\\Java\\apache-tomcat-9.0.27\\webapps\\YHY\\images\\xishi\\" + loaclhost_file_name),
                            new File("D:\\YHY\\web\\images\\xishi\\" + loaclhost_file_name));


                    /*调用sevice方法*/
                    /*封装参数*/
                    UploadBean uploadBean = new UploadBean();
                    uploadBean.setName(fileName);
                    uploadBean.setLoaclhost_file_name(loaclhost_file_name);
                    uploadBean.setUpload_those(upload_those);
                    uploadBean.setAccess_url(access_url);
                    uploadBean.setHref(href);
                    new UploadService().insertUpload(uploadBean);

                    map.put("code", "0");
                    map.put("msg", "成功");
                    map.put("url", "url");
                }
            }
        } catch (FileUploadException e) {
            map.put("code", "500");
            map.put("msg", "失败");
            map.put("url", "url");
            e.printStackTrace();
        } finally {
            if (bos != null && bis != null) {
                /*释放资源*/
                bos.close();
                bis.close();
            }
        }
        response.getWriter().write(new Gson().toJson(map));
    }

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

    private static String randomFileNanm(String name) {
        return UUID.randomUUID().toString().replace("-", "") + name;
    }

}

相关推荐