图片上传工具类

/**
 * Author: fuchunyu
 * Date: 2017/6/19
 * Description:fileInput上传专用接口
 */
public class UploadImage extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public static String getFilePath() {
        return "file/" + Convert.toShortYMDWithNoSplit(new Date()) + "/";
    }

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

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

    private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream os = response.getOutputStream();

        // 获得文件保存路径
    /*  String filePath = getFilePath();
        String path = getTempPath(filePath);
        */

        // 临时文件目录
        File temp = new File("/usr/local/temp/upload/");
        if (!temp.exists())
            temp.mkdirs();

        // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
        DiskFileItemFactory factory = new DiskFileItemFactory(5 * 1024 * 1024, temp);
        // 用以上工厂实例化上传组件
        ServletFileUpload sfu = new ServletFileUpload(factory);
        // 单个文件最大值
        sfu.setSizeMax(5* 1024 * 1024);

        List fileList = null;
        try {
            fileList = sfu.parseRequest(request);
        } catch (FileUploadException e) {
            if (e instanceof SizeLimitExceededException) {
                os.write("文件太大了".getBytes("UTF-8"));
                os.close();
                return;
            } else {
                os.write("未知异常".getBytes("UTF-8"));
                os.close();
                return;
            }
        }

        if (fileList == null || fileList.size() == 0) {
            os.write("请上传文件".getBytes("UTF-8"));
            os.close();
            return;
        }

        String fileNames = null;
        Iterator iter = fileList.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                String fileName = item.getName();
                if(fileName.lastIndexOf('.') == -1){
                    return;
                }
                String fileExt = fileName.substring(fileName.lastIndexOf('.'));
                if (!".png.jpg.jpeg.gif.bmp".contains(fileExt.toLowerCase())) {
                    os.write("文件类型错误".getBytes("UTF-8"));
                    os.close();
                    return;
                }
                fileName = getFileName() + fileExt;
                try {
                    // 这里将图片上传到oos服务器上面服务器上面
                    File file = File.createTempFile(fileName, fileExt);
                    file.deleteOnExit();
                    item.write(file);
                    //file.delete();


                    //item.write(new File(path, fileName));
                } catch (OSSException oe) {
                    System.out.println("Caught an OSSException, which means your request made it to OSS, "
                            + "but was rejected with an error response for some reason.");
                    System.out.println("Error Message: " + oe.getErrorCode());
                    System.out.println("Error Code:       " + oe.getErrorCode());
                    System.out.println("Request ID:      " + oe.getRequestId());
                    System.out.println("Host ID:           " + oe.getHostId());
                } catch (ClientException ce) {
                    System.out.println("Caught an ClientException, which means the client encountered "
                            + "a serious internal problem while trying to communicate with OSS, "
                            + "such as not being able to access the network.");
                    System.out.println("Error Message: " + ce.getMessage());
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                } finally {
            /*
             * Do not forget to shut down the client finally to release all allocated resources.
             */

                    client.shutdown();
                }
                //  fileName = AppConfig.RESOURCE_APP_ROOT + filePath + fileName;

                if (fileNames == null)
                    fileNames = fileName;
                else
                    fileNames += "," + fileName;
            }
        }
        os.write(("success" + "|"+ImagePath + fileNames).getBytes("UTF-8"));
        os.close();
        return;
    }

    public static String getTempPath(String filePath) {
        String projectName = AppConfig.PROJECT_NAME;
        String ret = AppConfig.getResourceHome();
        String contextPath = AppConfig.getContextPath();
        if (!contextPath.equals(projectName) && ret.contains(projectName)) {
            ret = ret.substring(0, ret.indexOf(projectName) - 1);
        }
        String path = ret + AppConfig.RESOURCE_APP_ROOT + filePath;
        // 文件上传目录
        File sourceFile = new File(path);
        if (!sourceFile.exists()) {
            sourceFile.mkdirs();
        }
        return path;
    }

    /**
     * 获取文件名
     * UUID 拼接 8位日期
     *
     * 如需获得原图,可将图片名称截后六位即图片创建日期,然后到file文件夹下根据日期即可找到
     * @return
     */
    public static String getFileName(){
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String time = Convert.toShortYMDWithNoSplit(new Date());
        return uuid + time;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值