JavaEE上传文件

一、搭建环境

  1、本文是在搭建web环境下,上传功能的,可以参考下搭建web环境

  Maven配置SpringMVC4+Spring4+Mybatis3环境 

  2、需要添加上传文件依赖的jar包

        <!-- Apache Commons FileUpload -->
        <!-- http://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- Apache Commons IO -->
        <!-- http://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
View Code

二、使用SpringMVC上传文件

  1、在初始化Spring容器中添加上传配置

    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- Maximum file size: 1MB -->
        <!-- 1MB = 125000 Byte -->
        <!--<property name="maxUploadSize" value="125000"/>-->
        <property name="defaultEncoding" value="utf-8"/>
    </bean>
View Code

  2、新建FileUploadController类

package com.moy.whymoy.test.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * [Project]:whymoy  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/3/13  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
@Controller
@RequestMapping("/upload")
public class FileUploadController {

    @RequestMapping("/doUpload")
    @ResponseBody
    public String uploadFileHandler(HttpServletRequest request,
                                    HttpServletResponse response,
                                    @RequestParam(value = "files") MultipartFile[] files) {

        String realPath = request.getServletContext().getRealPath("upload");
        File uploadRootPath = new File(realPath);
        if (!uploadRootPath.exists()) {
            uploadRootPath.mkdirs();
        }

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            String originalFilename = file.getOriginalFilename();
            try {
                File serverFile = new File(uploadRootPath, originalFilename);
                try (BufferedInputStream bis = new BufferedInputStream(file.getInputStream());
                     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(serverFile))) {
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while (-1 != (len = bis.read(buffer))) {
                        bos.write(buffer, 0, len);
                    }
                }
                sb.append("Upload File :").append(serverFile).append("\n");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
View Code

  3、在WEB-INF同级目录下,新建uploadFile.html(在同一站点下)

<html>
<head>
    <title>uploadOneFile</title>
</head>
<body>
<form method="POST" action="upload/doUpload.do" enctype="multipart/form-data">
    File to upload: <input type="file" name="files"><br/>
    <input type="submit" value="Upload">
</form>
</body>
</html>
View Code

  4、运行tomcat7插件访问uploadFile.html页面,测试上传

三、使用servlet上传

  1、新建UploadServlet类

package com.moy.whymoy.test.servlet;

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 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.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Objects;

/**
 * [Project]:whymoy  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/3/13  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
@WebServlet(urlPatterns = "/upload/servlet")
public class UploadServlet extends HttpServlet {

    // 上传目录
    private static String UPLOAD_DIR = "upload";
    // 默认编码
    private static String DEFAULT_ENCODING = "utf-8";
    // 内存临界值
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;  // 3MB
    // 上传文件最大值
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    // 请求最大值
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter writer = resp.getWriter();

        if (!ServletFileUpload.isMultipartContent(req)) {
            writer.println("需要为类型为:enctype=multipart/form-data");
            return;
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

        servletFileUpload.setSizeMax(MAX_REQUEST_SIZE);
        servletFileUpload.setFileSizeMax(MAX_FILE_SIZE);
        servletFileUpload.setHeaderEncoding(DEFAULT_ENCODING);

        String realPath = req.getServletContext().getRealPath(UPLOAD_DIR);
        File uploadRootPath = new File(realPath);
        if (!uploadRootPath.exists()) {
            uploadRootPath.mkdirs();
        }

        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);
            if (Objects.nonNull(fileItems)) {
                for (FileItem eachItem : fileItems) {
                    if (!eachItem.isFormField()) {
                        String fileName = new File(eachItem.getName()).getName();
                        File serverFile = new File(uploadRootPath, fileName);
                        eachItem.write(serverFile);
                        writer.println("Upload File :" + serverFile);
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
View Code

  2、在WEB-INF同级目录下,新建servletUploadFile.html(在同一站点下)

<html>
<head>
    <title>uploadOneFile</title>
</head>
<body>
<form method="POST" action="upload/servlet" enctype="multipart/form-data">
    File to upload: <input type="file" name="files"><br/>
    <input type="submit" value="Upload">
</form>
</body>
</html>
View Code

  3、运行tomcat7插件访问servletUploadFile.html页面,测试上传

四、异步上传

  1、在WEB-INF同级目录下,添加jquery.js库和新建ajax.html(在同一站点下)

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
    <script type="text/javascript" src="./jquery.js"></script>
</head>
<body>
    <form  id="form1" method="POST" action="http://192.168.182.130:8080/whymoy/upload/servlet" enctype="multipart/form-data">
    File to upload: <input type="file" name="files"><br/>
        <input type="submit" value="表单同步上传">
    </form><br/>

    <input id="ajaxUpload" type="button" value="异步上传"> <br/>
    <div id="result" style="color: red">
        
    </div>

    <script type="text/javascript">
        $(function(){
            $("#ajaxUpload").click(function(){
                $.ajax({
                    url:"http://192.168.182.130:8080/whymoy/upload/doUpload.do",
                    type: 'POST',
                    cache: false,
                    data: new FormData($('#form1')[0]),
                    processData: false,
                    contentType: false,
                    success:function(data){
                        $("#result").text(data);
                    }
                })
            });
        });
    </script>
</body>
</html>
View Code

  2、运行tomcat7插件访问ajax.html页面,测试上传

五、跨域异步上传

  1、第四步是可以满足异步上传的,只是进入不了回调函数,想要进入回调函数,可以响应时添加对应的响应头,可以参考

  JavaEE从服务器端解决Ajax跨域问题

 六、也可以直接使用httpClient,获取文件流,直接上传

  1、添加依赖

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.3</version>
        </dependency>
View Code

  2、测试代码

package com.moy.whymoy.test;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;

/**
 * [Project]:whymoy  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/3/14  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public class Main {

    public static void main(String[] args) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault();) {
            File file = new File("pom.xml");
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.addBinaryBody("files", file);
            HttpEntity httpEntity = entityBuilder.build();

            String uploadUrl = "http://localhost:8080/whymoy/upload/doUpload.do";
            HttpPost httpPost = new HttpPost(uploadUrl);
            httpPost.setEntity(httpEntity);

            CloseableHttpResponse response = httpClient.execute(httpPost);
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
        }
    }
}
View Code

 

yexiangyang

moyyexy@gmail.com


 

posted @ 2018-03-14 22:40  墨阳  阅读(1072)  评论(0编辑  收藏  举报