一、搭建环境
1、本文是在搭建web环境下,上传功能的,可以参考下搭建web环境
2、需要添加上传文件依赖的jar包
commons-fileupload
commons-fileupload
1.3.1
commons-io
commons-io
2.4
View Code
二、使用SpringMVC上传文件
1、在初始化Spring容器中添加上传配置
View Code
2、新建FileUploadController类
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(在同一站点下)
uploadOneFileFile to upload:
View Code
4、运行tomcat7插件访问uploadFile.html页面,测试上传
三、使用servlet上传
1、新建UploadServlet类
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(在同一站点下)
uploadOneFileFile to upload:View Code
3、运行tomcat7插件访问servletUploadFile.html页面,测试上传
四、异步上传
1、在WEB-INF同级目录下,添加jquery.js库和新建ajax.html(在同一站点下)
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、添加依赖
org.apache.httpcomponents
httpclient
4.5.3
org.apache.httpcomponents
httpmime
4.5.3
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
* [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