search
HomeJavaJavaBaseHow to upload files in java

How to upload files in java

Nov 14, 2019 am 11:58 AM
java

How to upload files in java

There are many ways to upload files in Java, the simplest ones are still FileInputStream and FileOutputStream. Here I list 3 common file upload method codes

First of all, using the springMVC native file upload method requires some simple configuration. Not much to say, as shown above. (Recommended learning: java course)

How to upload files in java1. Use the method of uploading files provided by spring

@RequestMapping("springUpload")
    public String  springUpload(HttpServletRequest request) throws IllegalStateException, IOException
    {
         long  startTime=System.currentTimeMillis();
         //将当前上下文初始化给  CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
           //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                    String path="E:/springUpload"+file.getOriginalFilename();
                    //上传
                    file.transferTo(new File(path));
                } 
            }
        }
        long  endTime=System.currentTimeMillis();
        System.out.println("Spring方法的运行时间:"+String.valueOf(endTime-startTime)+"ms");
        return "/success"; 
    }

2. Use file.Transto to save uploaded files. This is currently the best upload method in my opinion, and it is also my favorite upload method. The code is simple and the speed is fast. Please see the code below.

/*
     * 采用file.Transto 来保存上传的文件
     */
    @RequestMapping("fileUpload2")
    public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file) throws IOException {
         long  startTime=System.currentTimeMillis();
        System.out.println("fileName:"+file.getOriginalFilename());
        String path="E:/"+new Date().getTime()+file.getOriginalFilename();
          
        File newFile=new File(path);
        //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
        file.transferTo(newFile);
        long  endTime=System.currentTimeMillis();
        System.out.println("采用file.Transto的运行时间:"+String.valueOf(endTime-startTime)+"ms");
        return "/success"; 
    }

3. The third method is to upload by stream. This method is often used by novices when learning, but I don’t like it because it is slow and difficult to write. Please see

@RequestMapping("fileUpload")
    public String  fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IOException {
          
        //用来检测程序运行时间
        long  startTime=System.currentTimeMillis();
        System.out.println("fileName:"+file.getOriginalFilename());
          
        try {
            //获取输出流
            OutputStream os=new FileOutputStream("E:/"+new Date().getTime()+file.getOriginalFilename());
            //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
            InputStream is=file.getInputStream();
            byte[] bts = new byte[1024];
            //一个一个字节的读取并写入
            while(is.read(bts)!=-1)
            {
                os.write(bts);
            }
           os.flush();
           os.close();
           is.close();
          
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        long  endTime=System.currentTimeMillis();
        System.out.println("采用流上传的方式的运行时间:"+String.valueOf(endTime-startTime)+"ms");
        return "/success"; 
    }

Simple file upload page

How to upload files in java

The above is the detailed content of How to upload files in java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are different garbage collection algorithms in Java (Serial, Parallel, CMS, G1, ZGC)?What are different garbage collection algorithms in Java (Serial, Parallel, CMS, G1, ZGC)?Mar 14, 2025 pm 05:06 PM

The article discusses various Java garbage collection algorithms (Serial, Parallel, CMS, G1, ZGC), their performance impacts, and suitability for applications with large heaps.

What is the Java Virtual Machine (JVM) and how does it work internally?What is the Java Virtual Machine (JVM) and how does it work internally?Mar 14, 2025 pm 05:05 PM

The article discusses the Java Virtual Machine (JVM), detailing its role in running Java programs across different platforms. It explains the JVM's internal processes, key components, memory management, garbage collection, and performance optimizatio

How do I use Java's Nashorn engine for scripting with JavaScript?How do I use Java's Nashorn engine for scripting with JavaScript?Mar 14, 2025 pm 05:00 PM

Java's Nashorn engine enables JavaScript scripting within Java apps. Key steps include setting up Nashorn, managing scripts, and optimizing performance. Main issues involve security, memory management, and future compatibility due to Nashorn's deprec

How do I use Java's try-with-resources statement for automatic resource management?How do I use Java's try-with-resources statement for automatic resource management?Mar 14, 2025 pm 04:59 PM

Java's try-with-resources simplifies resource management by automatically closing resources like file streams or database connections, improving code readability and maintainability.

How do I use Java's enums to represent fixed sets of values?How do I use Java's enums to represent fixed sets of values?Mar 14, 2025 pm 04:57 PM

Java enums represent fixed sets of values, offering type safety, readability, and additional functionality through custom methods and constructors. They enhance code organization and can be used in switch statements for efficient value handling.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software