文件上传---普通文件和url文件

主要用来学习使用common-fileupload.jar和java.net.httpURLConnection

普通文件:

//上传xls文件到临时目录
        if (! ServletFileUpload.isMultipartContent(request)) return;
        DiskFileItemFactory factory = new DiskFileItemFactory();  // 建立factory
        factory.setSizeThreshold(4*1024*1024);  // 设定缓存大小
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(5120000);//5M

        File srcFile = null;
        try {
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    String ext = StringUtils.substringAfterLast(item.getName(), ".").toLowerCase();
                    //过滤文件格式
                    if(StringUtils.isEmpty(ext) || !"xls".equalsIgnoreCase(ext)) {
                        System.out.println("Unsupport file type: "+ext);
                        throw new Exception("Unsupport file type: "+ext);
                    }

                    String fileName = Long.toString(Calendar.getInstance().getTimeInMillis())+"."+ext;
                   //临时目录
                   String srcFilePath = "/tmp/" + fileName;
                   srcFile = new File(srcFilePath);
                   if (srcFile.exists()) {
                       continue;
                   }
                   item.write(srcFile);
                }
            }
        }catch (SizeLimitExceededException e){
            e.printStackTrace();
            return;
        }catch (FileUploadException fupEx) {
            fupEx.printStackTrace();
            return;
        }

url文件上传:

System.out.println("Upload url file begins ");
    try {
        String srcURL = request.getParameter("srcURL");
        if(srcURL==null || srcURL.trim().length()<=0) {
            throw new Exception("No url found ");
        }

        String ext = StringUtils.substringAfterLast(srcURL, ".").toLowerCase();
        //初级过滤文件格式
        if(app.getFileExts()!=null && !app.getFileExts().contains(ext)) {
            throw new Exception("Unsupport file type: "+ext);
        }

        String fileName = Long.toString(Calendar.getInstance().getTimeInMillis())+"."+ext;
        String srcFilePath = "/tmp/" + fileName;

        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File saveFile = new File(srcFilePath);

        //file wall
        String proxy = "192.168.1.1";
        String port = "8080";
        Properties systemProperties = System.getProperties();
        systemProperties.setProperty("http.proxyHost",proxy);
        systemProperties.setProperty("http.proxyPort",port);

        try{
            urlfile = new URL(srcURL);
            httpUrl = (HttpURLConnection)urlfile.openConnection();

            httpUrl.setConnectTimeout(3000);
            httpUrl.setReadTimeout(60000);

            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
        }catch(Exception e)
        {
            e.printStackTrace();
            System.out.println("Souce url connect failed:"+srcURL+" by "+e.getMessage());
            return;
        }

        try{
            int count = 0;
            int size = 0;
            bos = new BufferedOutputStream(new FileOutputStream(saveFile));
            byte[] b = new byte[1024];
            while((count=bis.read(b))!=-1) {
                bos.write(b, 0, count);
                size +=count;
                if(size>=app.getFileSize()) {
                    System.out.println("File size exceeded max limit ");
                    return;
                }
            }
        }catch(Exception e)
        {
            e.printStackTrace();
            System.out.println("Save url file failed:"+srcURL+" by "+e.getMessage());
            return;
        }finally{
            try{
                bos.flush();
                bis.close();
                httpUrl.disconnect();
            }catch(Exception e)
            {
                System.out.println(e.toString());
            }
        }

更多详细关于HttpURLConnection的学习资料请参考:

HttpURLConnection学习

JDK中的URLConnection参数详解

时间: 2024-08-08 01:11:14

文件上传---普通文件和url文件的相关文章

Java实现文件上传(验证文件大小、文件类型)

文件上传是每个java开发者必须掌握的.文件上传有很多种实现方式,但其实也大同小异.笔人在这里为大家介绍一种我习惯用的,上传文件的方式.大家先看代码,最后我会分享我的源码给大家. 1.首先要准备一下需要用到的jar包. commons-fileupload-1.2.1.jar -commons-io-1.4.jar 可以从[(http://commons.apache.org/)]下载,当然,我的项目源码里也有 然后开始写代码. public static String fileUpload(H

aspx 文件上传和下载,多文件上传

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultiFileUpload.aspx.cs"  Inherits="MultiFileUpload"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org

【FTP】java FTPClient 文件上传内容为空,文件大小为0

问题:如题所述,使用FTPClient上传至FTP服务器, 表现如下:①文件大小为0 ②上传很小的文件,但是要花费很长的时间,20K要花费2分钟甚至更久 ③没有任何的报错,没有任何的乱码 解决方法: [参考:http://blog.csdn.net/tengdazhang770960436/article/details/43274001] 如果你在本地的 Java 项目里面去用 FtpClient 上传文件,然后虽然文件上传上去了,但是文件里面没有内容,那么这说明你的机器防火墙设置有问题如下图

结合项目(Spring+(基于注解的)SpringMVC和Mybatis+uploadify文件上传)--poi解析Excel文件

poi解析Excel文件 1.上传文件至服务器 2.解析Excel文件并返回数据集合 3.将数据保存到服务器 框架======Spring+(基于注解的)SpringMVC和Mybatis===== 第一步: 前台: jsp文件采用的是uploadify <div id="fileQueue"></div> <input type="file" id="brandFile"> js: <script ty

十九、多文件上传(ajaxFileupload实现多文件上传功能)

来源于https://www.jb51.net/article/128647.htm 打开google 搜索"ajaxFileupload' '多文件上传"可以搜到许许多多类似的,那我为什么还要写一下呢?一个是对之前大神的贡献表示感谢:二个是自己知识的总结:三个是自己在原有的基础上改动了下,在此记录,可能帮助其他朋友. 用过这个插件的都知道这个插件的基本用法,我就不废话,直接上代码. 我需要实现多个文件上传,之前的做法是定义多个不同id的input,然后把ajaxfileuplod方法

ASP.NET Core WEB API 使用element-ui文件上传组件el-upload执行手动文件文件,并在文件上传后清空文件

前言: 从开始学习Vue到使用element-ui-admin已经有将近快两年的时间了,在之前的开发中使用element-ui上传组件el-upload都是直接使用文件选取后立即选择上传,今天刚好做了一个和之前类似的文件选择上传的需求,不过这次是需要手动点击按钮把文件上传到服务器中进行数据导入,而且最多只能够选择一个文件进行上传,上传成功后需要对file-list中的文件列表数据进行清空操作,在这里服务端使用的是ASP.NET Core WEB API来进行文件流数据接收和保存. 一.简单概述e

文件上传如何合理地验证文件类型?

在网上搜了一下,一般都是通过文件后缀名判断,很显而易见的是用户通过修改后缀名来逃避,我想问的问题有两个: 还有什么验证文件类型的方法? 攻击者利用后缀名漏洞能造成什么样的危害? 在网上找到的攻击方式有: 修改后缀名(exe->jpg), 多后缀名(test.php.fr), 后缀名大小写(php->pHp), 代码嵌入(图片里注入php代码), null字符(00) 相对路径(../../../) 知乎用户-江南回答 其实对于防御者来说,其实不用这么费劲来进行验证 时间戳+随机数+.jpg后缀

php文件上传参考配置与大文件上传

PHP用超级全局变量数组$_FILES来记录文件上传相关信息的,在php文件上传之前,可通过调节php.ini中相关配置指令,来控制上传相关细节. 1.file_uploads=on/off   是否允许通过http方式上传文件 2.max_execution_time=30   允许脚本最大执行时间,超过这个时间就会报错 3.memory_limit=50M   设置脚本可以分配的最大内存量,防止失控脚本占用过多内存,此指令只有在编译时设置了    --enable-memory-limit标

文件上传,服务端压缩文件方法,重点是png与gif图片的压缩,保证了透明度与动画

1 /// <summary> 2 /// 上传文件帮助类 3 /// </summary> 4 public class ImageUploadHelper 5 { 6 7 #region SaveVideoFirstImg 根据视频路径生成视频对应的图片 8 /// <summary> 9 /// 根据视频路径生成视频对应的图片 10 /// </summary> 11 /// <param name="videoUrl">

php实现文件上传,下载的常见文件配置

配置文件,php.ini uploadfile  post_max_size 规定表单上传的最大文件: