java服务端接收文件

总结:

客户端和服务端,全部使用Content-Type: multipart/form-data标识form中的文件字段,每个文件有不同的form表单名字

参考自:

https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/Java-File-Upload-Servlet-Ajax-Example#:~:text=Java%20file%20uploaders&text=Code%20a%20Java%20Servlet%20to,that%20the%20file%20successfully%20uploaded.

inputstream转byte数组,参考自:
https://stackoverflow.com/questions/1264709/convert-inputstream-to-byte-array-in-java


pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>fileupload</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <username>tomcat</username>
                    <password>tomcat</password>
                    <uriEncoding>UTF-8</uriEncoding>
                    <protocol>org.apache.coyote.http11.Http11NioProtocol</protocol>
                    <path>/</path>
                    <port>8080</port>
                </configuration>
            </plugin>
            <!-- -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <outputFileNameMapping>@{artifactId}@.@{extension}@</outputFileNameMapping>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.3.0.M2</version>
                <configuration>
                    <httpConnector>
                        <port>8090</port>
                    </httpConnector>
                    <stopPort>9966</stopPort>
                    <stopKey>foo</stopKey>
                    <scanIntervalSeconds>0</scanIntervalSeconds>
                    <webAppConfig>
                        <contextPath>/</contextPath>
                    </webAppConfig>
                </configuration>

            </plugin>

        </plugins>
    </build>
</project>


服务端:


package com.mcnz.web;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
/* The Java file upload Servlet example */

@WebServlet(name = "FileUploadServlet", urlPatterns = { "/fileuploadservlet" })
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
        maxFileSize = 1024 * 1024 * 10,      // 10 MB
        maxRequestSize = 1024 * 1024 * 100   // 100 MB
)
public class FileUploadServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        /* Receive file uploaded to the Servlet from the HTML5 form */
        Part filePart = request.getPart("file");
        String fileName = filePart.getSubmittedFileName();
        for (Part part : request.getParts()) {
            //part.write("C:\\upload\\" + fileName);
//            part.write("/Users/xxx/Desktop/" + fileName);
            byte[] bytes = readAllBytes(part.getInputStream());
            System.out.println(bytes);

        }
        response.getWriter().print("The file uploaded sucessfully.");
    }


    public byte[] readAllBytes(InputStream inputStream) throws IOException {
        final int bufLen = 4 * 0x400; // 4KB
        byte[] buf = new byte[bufLen];
        int readLen;
        IOException exception = null;

        try {
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                while ((readLen = inputStream.read(buf, 0, bufLen)) != -1)
                    outputStream.write(buf, 0, readLen);

                return outputStream.toByteArray();
            }
        } catch (IOException e) {
            exception = e;
            throw e;
        } finally {
            if (exception == null) inputStream.close();
            else try {
                inputStream.close();
            } catch (IOException e) {
                exception.addSuppressed(e);
            }
        }
    }

}


http测试,使用idea中rest工具:
POST http://localhost:8090/fileuploadservlet
Content-Type: multipart/form-data; boundary=WebAppBoundary

--WebAppBoundary
Content-Disposition: form-data; name="file"; filename="wxpng"

< /Users/xxx/Desktop/xxxxx.png
--WebAppBoundary--


使用idea发送restful,上传文件参考:
https://stackoverflow.com/questions/34384650/intellij-idea-rest-client-file-uploading


浏览器中:
<!DOCTYPE html> 
<html> 
<head> 
<title> Java File Upload Servlet Example </title> 
</head> 
<body>

  <form method="post" action="http://127.0.0.1:8090/fileuploadservlet" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
  </form>

</body>
</html>

将图片返回给浏览器中:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        /* Receive file uploaded to the Servlet from the HTML5 form */
        Part filePart = request.getPart("file");
        String fileName = filePart.getSubmittedFileName();
        byte[] bytes = null;
        for (Part part : request.getParts()) {
            //part.write("C:\\upload\\" + fileName);
//            part.write("/Users/xxx/Desktop/" + fileName);
            bytes = readAllBytes(part.getInputStream());
            System.out.println(bytes);

        }
//        response.getWriter().print("The file uploaded sucessfully.");
        response.getOutputStream().write(bytes);
    }

参考自:
https://docs.oracle.com/javaee/6/tutorial/doc/glraq.html

While social media websites such Facebook and LinkedIn made it incredibly easy for a user to upload image files, the back-end implementation of such a feature has been anything but easy. Prior to the Java EE 7 release, developers struggled to implement a Servlet file upload component because it was a rather sordid affair that required a great deal of error-prone and bloated code.

Fortunately, the Servlet 3.1 release changed all that for developers with Java file upload concerns.

Java file uploaders

You will need to perform the following steps to create a Java Servlet file upload component:

  1. Create a basic HTML or JSP file that contains an HTML5 file input form element;
  2. From the form, invoke a Java Servlet to handle the server-side processing of the file;
  3. Code a Java Servlet to handle the file upload process;
  4. Annotate the file upload Servlet with the @MultipartConfig annotation;
  5. In the Servlet, save the uploaded file to the server’s file system; and
  6. Send a response back to the browser to indicate that the file successfully uploaded.

HTML5 file input tags

The HTML5 file input type tag makes it possible to render a file selector in any modern browser. A programmer should include the input tag within an HTML5 form tag whose action attribute points to a file upload Servlet and set the enclosing form’s enctype attribute to be multipart/form-data. Then, the developer should add a submit button and the HTML component required to upload a file from a browser to a Java Servlet is complete.

Save the following code in a file named input.html and save it to the webapps folder of your Java web module.

<!DOCTYPE html> 
<html> 
<head> 
<title> Java File Upload Servlet Example </title> 
</head> 
<body>

  <form method="post" action="fileuploadservlet" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
  </form>

</body>
</html>

The file upload Servlet

The Java file upload Servlet will contain a doPost method to handle the form submission. In this doPost method, the uploaded file will process in parts. After the file uploads, the Java Servlet saves each part to a like-named file in the C:\upload\ folder on the server’s file system.

More File Upload Options

I put together a bunch of file upload tutorials. Pick your technology and get uploading!

Uploading files to the server need not be a problem.

The Servlet provides multipart processing capabilities through the addition of the @MultipartConfig annotation at the start of the class. This annotation also allows the developer to set various file upload properties, such as the maxFileSize, maxRequestSize and the fileSizeThreshold.

The complete code for the file upload Servlet looks like this:

package com.mcnz.web;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
/* The Java file upload Servlet example */

@WebServlet(name = "FileUploadServlet", urlPatterns = { "/fileuploadservlet" })
@MultipartConfig(
  fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
  maxFileSize = 1024 * 1024 * 10,      // 10 MB
  maxRequestSize = 1024 * 1024 * 100   // 100 MB
)
public class FileUploadServlet extends HttpServlet {

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    /* Receive file uploaded to the Servlet from the HTML5 form */
    Part filePart = request.getPart("file");
    String fileName = filePart.getSubmittedFileName();
    for (Part part : request.getParts()) {
      part.write("C:\\upload\\" + fileName);
    }
    response.getWriter().print("The file uploaded sucessfully.");
  }

}

Run the Java Servlet file upload example

With the Java Servlet coded, the application can be deployed to any Java application server that supports the Servlet 3.1 specification or newer. In this Java file upload example, the target server is Tomcat 9, although the latest JBoss, Jetty, WebSphere or OpenLiberty servers will also work.

When the application runs, a file selector will appear in the user’s browser. The user can then select a file from their computer and click the “Upload” button to submit the file to the server. The Java file upload Servlet will then capture that file and persist it to the C:\uploads folder on the server.

An Ajax and Java file upload component allows for asynchronous file uploads from the browser.

Java and Ajax file uploads

If you want to get fancy and perform an asynchronous file upload with Java, add Ajax functionality by editing the HTML file. If you replace the markup in HTML file with what’s below, the request-response cycle will be asynchronous and the user will never have to navigate away from the original page.

<!DOCTYPE html> 
<html> 
<head> 
<title> Java Ajax File Upload Example </title> 
</head> 
<body>
  <!-- HTML5 Input Form Elements -->
  <input id="ajaxfile" type="file"/> <br/>
  <button οnclick="uploadFile()"> Upload </button>

  <!-- Ajax to Java File Upload Logic -->
  <script>
  async function uploadFile() {
    let formData = new FormData(); 
    formData.append("file", ajaxfile.files[0]);
    await fetch('fileuploadservlet', {
      method: "POST", 
      body: formData
    }); 
    alert('The file upload with Ajax and Java was a success!');
  }
  </script>
</body> 
</html>

File uploads with Java

The Servlet 3.1 API and the HTML5 specification have made it incredibly easy to add Java and Servlet file upload functionality to modern web apps. If a user needs to upload images and documents to be managed on the server, it’s quick and easy for a developer to solve the problem with a Java-based web offering.

The following Maven POM file was used to build the Java Servlet file upload example:

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.mcnz</groupId>
 <artifactId>java-file-upload-example</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>

 <dependencies>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>4.0.1</version>
  </dependency>

 </dependencies>

 <build>
  <plugins>
   <plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <version>3.2.0</version>
   </plugin>

   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.3.1</version>
    <configuration>
      <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
   </plugin>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值