Java Servlet3.0使用getPart/getParts实现单文件和多文件上传
Part类的官方文档
选择文件 点击上传 参数名为 file,用于后端获取
<div>
<input type="file" id="file" value="文件上传"/>
div>
<div>
<button type="button" id="upload">Uploadbutton>
div>
单文件上传
var uploadFile;
$(function() {
$('#file').on('change', function() {
var files = this.files;
if (files.length == 0) {
return;
}
uploadFile = files[0];
});
$('#upload').on('click', function() {
var formData = new FormData();
formData.append("file", uploadFile); // 后端通过 'file' 获取
$.ajax({
url: 'http://localhost/Test/upload',
data: formData,
type: "post",
processData: false, //必须false才会避开jQuery对 formdata 的默认处理 XMLHttpRequest会对 formdata 进行正确的处理
contentType: false, //必须false才会自动加上正确的Content-Type
success: function(result) {
console.log(result);
}
});
});
});
@MultipartConfig 这个注解必须加上
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet("/upload")
@MultipartConfig
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
Part part = request.getPart("file"); // 获取文件
// 原文件名在头信息的Content-Disposition中
// Content-Disposition:form-data; name="photo"; filename="测试文件.txt"
String header = part.getHeader("Content-Disposition");
// 获取原文件名
int start = header.lastIndexOf("=")+1;
String name = header.substring(start).replace("\"", "");
// 生成随机文件名
String filename = MD5.MD5Encode(UUID.randomUUID().toString(), "utf-8") + "@" + name;
// 文件存放路径
String savePath = "";
if (fileName != null && !"".equals(fileName)) {
// 写入磁盘
part.write(savePath + File.separator + fileName);
}
out.print("ok");
out.flush();
out.close();
}
}
MD5
package com.util;
import java.security.MessageDigest;
/**
* MD5加密
* @Author:Starry
* @Description:
* @Date:Created in 9:46 2018/4/13 Modified By:
*/
public class MD5 {
private static final String hexDigIts[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
"e", "f" };
/**
* MD5加密
*
* @param origin
* 字符
* @param charsetname
* 编码
* @return
*/
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (null == charsetname || "".equals(charsetname)) {
resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
} else {
resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
}
} catch (Exception e) {
}
return resultString;
}
public static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}
public static String byteToHexString(byte b) {
int n = b;
if (n < 0) {
n += 256;
}
int d1 = n / 16;
int d2 = n % 16;
return hexDigIts[d1] + hexDigIts[d2];
}
}
和单文件差不多 就是多传了参length,代表文件的数量
<style type="text/css">
#container span {
margin-right: 10px;
}
#container .remove {
cursor: pointer;
color: red;
}
style>
<body>
<div>
<input type="file" id="file" value="文件上传"/>
div>
<div id="container">div>
<div>
<button type="button" id="upload">Uploadbutton>
div>
body>
// 文件列表
var uploadFiles = new Array();
// 数组删除元素
Array.prototype.remove = function(index) {
if (index > -1) {
this.splice(index, 1);
}
};
$(function() {
$('#file').on('change', function() {
var files = this.files;
if (files.length == 0) {
return;
}
var file = files[0];
var parent = document.createElement("div"), //容器
name = document.createElement("span"), //文件名
remove = document.createElement("span"); //删除
name.innerHTML = file.name;
remove.innerHTML = 'x';
remove.className = 'remove';
parent.appendChild(name);
parent.appendChild(remove);
$('#container').append(parent);
uploadFiles[length] = file;
$(this).val("");
});
$('#container').on('click', '.remove', function() {
var index = $(this).parent().index();
uploadFiles.remove(index);
$(this).parent().remove();
});
$('#upload').on('click', function() {
var formData = new FormData();
for (var i = 0; i < uploadFiles.length; i++) {
formData.append("file" + i, uploadFiles[i]);
}
formData.append("length", uploadFiles.length);
$.ajax({
url: 'http://localhost/Test/upload',
data: formData,
type: "post",
processData: false, //必须false才会避开jQuery对 formdata 的默认处理 XMLHttpRequest会对 formdata 进行正确的处理
contentType: false, //必须false才会自动加上正确的Content-Type
success: function(result) {
console.log(result);
}
});
});
});
// 文件数量
int length = Integer.parseInt(request.getParameter("length"));
// 文件列表
List<Part> parts = new ArrayList<Part>();
for (int i = 0; i < length; i++) {
parts.add(request.getPart("file" + i));
}
$('body').on('change', '#file', function() {
var length = $("#container>div").length;
if (length == 9) {
alert('最多选择9张图片');
$(this).val('');
return false;
}
var files = this.files;
if (files.length == 0) {
return;
}
var file = files[0];
var type = file.type;
if (type != 'image/png' && type != 'image/jpeg' && type != 'image/jpg') {
alert('请选择png或jpg格式');
$(this).val('');
return false;
}
//每次都只会遍历一个图片数据
var div = document.createElement('div'), // 容器
img = document.createElement('img'); // 图片
i = document.createElement('i'); // 删除
i.className = 'remove';
div.appendChild(i);
var fr = new FileReader();
fr.onload = function() {
img.src = this.result;
div.appendChild(img);
$('#container').append(div);
}
fr.readAsDataURL(file);
uploadFiles[length] = file;
$(this).val('');
});