java ee 上传文件_JavaEE上传文件

本文详细介绍了在Java EE环境中实现文件上传的多种方法,包括使用SpringMVC、Servlet以及异步上传。通过实例代码展示了如何处理上传文件,以及如何进行跨域异步上传。还提到了使用httpClient进行文件流上传的解决方案。
摘要由CSDN通过智能技术生成

一、搭建环境

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

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

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

commons-fileupload

commons-fileupload

1.3.1

commons-io

commons-io

2.4

View Code

二、使用SpringMVC上传文件

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

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

View Code

2、新建FileUploadController类

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.moy.whymoy.test.controller;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.ResponseBody;importorg.springframework.web.multipart.MultipartFile;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;import java.io.*;/*** [Project]:whymoy

* [Email]:moy25@foxmail.com

* [Date]:2018/3/13

* [Description]:

*

*@authorYeXiangYang*/@Controller

@RequestMapping("/upload")public classFileUploadController {

@RequestMapping("/doUpload")

@ResponseBodypublicString uploadFileHandler(HttpServletRequest request,

HttpServletResponse response,

@RequestParam(value= "files") MultipartFile[] files) {

String realPath= request.getServletContext().getRealPath("upload");

File uploadRootPath= newFile(realPath);if (!uploadRootPath.exists()) {

uploadRootPath.mkdirs();

}

StringBuilder sb= newStringBuilder();for (int i = 0; i < files.length; i++) {

MultipartFile file=files[i];

String originalFilename=file.getOriginalFilename();try{

File serverFile= newFile(uploadRootPath, originalFilename);try (BufferedInputStream bis = newBufferedInputStream(file.getInputStream());

BufferedOutputStream bos= new BufferedOutputStream(newFileOutputStream(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();

}

}returnsb.toString();

}

}

View Code

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

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

uploadOneFile

File to upload:

View Code

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

三、使用servlet上传

1、新建UploadServlet类

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.moy.whymoy.test.servlet;importorg.apache.commons.fileupload.FileItem;importorg.apache.commons.fileupload.FileUploadException;importorg.apache.commons.fileupload.disk.DiskFileItemFactory;importorg.apache.commons.fileupload.servlet.ServletFileUpload;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.File;importjava.io.IOException;importjava.io.PrintWriter;importjava.util.List;importjava.util.Objects;/*** [Project]:whymoy

* [Email]:moy25@foxmail.com

* [Date]:2018/3/13

* [Description]:

*

*@authorYeXiangYang*/@WebServlet(urlPatterns= "/upload/servlet")public class UploadServlet extendsHttpServlet {//上传目录

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

@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {

PrintWriter writer=resp.getWriter();if (!ServletFileUpload.isMultipartContent(req)) {

writer.println("需要为类型为:enctype=multipart/form-data");return;

}

DiskFileItemFactory factory= newDiskFileItemFactory();

factory.setSizeThreshold(MEMORY_THRESHOLD);

ServletFileUpload servletFileUpload= newServletFileUpload(factory);

servletFileUpload.setSizeMax(MAX_REQUEST_SIZE);

servletFileUpload.setFileSizeMax(MAX_FILE_SIZE);

servletFileUpload.setHeaderEncoding(DEFAULT_ENCODING);

String realPath=req.getServletContext().getRealPath(UPLOAD_DIR);

File uploadRootPath= newFile(realPath);if (!uploadRootPath.exists()) {

uploadRootPath.mkdirs();

}try{

List fileItems =servletFileUpload.parseRequest(req);if(Objects.nonNull(fileItems)) {for(FileItem eachItem : fileItems) {if (!eachItem.isFormField()) {

String fileName= newFile(eachItem.getName()).getName();

File serverFile= newFile(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(在同一站点下)

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

uploadOneFileFile to upload:

View Code

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

四、异步上传

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

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

testFile to upload:

$("#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);

}

})

});

});

View Code

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

五、跨域异步上传

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

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

1、添加依赖

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

org.apache.httpcomponents

httpclient

4.5.3

org.apache.httpcomponents

httpmime

4.5.3

View Code

2、测试代码

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

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
* [Email]:moy25@foxmail.com
* [Date]:2018/3/14
* [Description]:
*

* @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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值