HTML5前端代码
<form enctype="multipart/form-data" >
<div style="float:left;">
<input type="file"
accept="image/*" multiple="multiple"
style="width: 310px;height:280px;cursor: pointer;opacity:0;position: absolute;"/>
<div class="bad"></div>
</div>
</form>
<div id="images">
</div>
js脚本
$(function(){
$('input[type=file]').change(function() {
if(validateUploadFile(this) == 1){
uploadFile('20', this);
}else{
console.log("不能上传!");
}
});
});
function uploadFile(busiType, obj){
var formData = new FormData();
formData.append('imageNum', obj.files.length);
for(var i = 0; i != obj.files.length; i++){
formData.append('image' + i, obj.files[i]);
}
formData.append('busiType',busiType);
$.ajax({
url: '/rest/file/upload/multiple',//Server script to process data
type: 'POST',
//Ajax events
beforeSend: function(){},
success: function(data){
console.log(data);
if(data == -1){
alert("上传失败");
}
var paths = data.split(",");
for(var i = 0; i != paths.length ; i++){
$('#images').append('<li><img src="'+ paths[i] +'" style="width: 220px;height: 165px;"></img></li>');
}
},
error: function(){
alert("上传失败");
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
}
function validateUploadFile(obj){
if (obj == null || $(obj).val() === "") {
alert("请上传图片文件!(最多9张)");
return 0;
}
if(obj.files.length > 9){
alert("只能上传9张图片!")
return 0;
}
var regex = new RegExp("(.*?)\.(png|jpg|jpeg|gif)$"),
errors = [];
console.log("上传限制文件大小:5MB。");
//检查多张图片的大小与类型
for(var i = 0;i != obj.files.length; i++){
var file = obj.files[i],
val = $(obj).val().trim().toLowerCase();
var name = file.name;
var size = file.size / 1024 / 1024;
var type = file.type;
console.log("正在检测: 文件名:" + name + " ,文件类型: " + type + " ,文件大小为: " + size + " MB。");
if (size > 5) {
errors.push("文件: " + name + "." + type +" 超出上传限制文件大小(" + size + "MB)" );
}
if (!(regex.test(val))) {
errors.push("文件: " + name + "." + type + "不是图片文件。(能上传的图片文件格式为png,jpg,jpeg和gif)");
}
}
if (errors.length > 0) {
$(obj).val('');
alert(errors.join('\r\n'));
return 0;
}
return 1;
}
RESTEasy后端
@POST
@Path("/upload/multiple")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadMultipleFile(MultipartFormDataInput input){
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
Date now = new Date();
int year = Tools.getYearOrMonthOfDate(now, Calendar.YEAR);
int month = Tools.getYearOrMonthOfDate(now, Calendar.MONTH);
List<InputPart> busiTypeParts = uploadForm.get("busiType");
String typeCode = "";
//获取业务类型代号
for(InputPart inputPart : busiTypeParts){
try {
typeCode = inputPart.getBody(String.class, null);
} catch (IOException e) {
e.printStackTrace();
return "-1";
}
}
//获取图片数
List<InputPart> imageNumParts = uploadForm.get("imageNum");
int imageNum = 0;
for(InputPart inputPart : imageNumParts){
try {
imageNum = inputPart.getBody(int.class, null);
} catch (IOException e) {
e.printStackTrace();
return "-1";
}
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i != imageNum; i++){
List<InputPart> imageParts = uploadForm.get("image"+i);
for (InputPart inputPart : imageParts) {
try {
MultivaluedMap<String, String> header = inputPart.getHeaders();
byte[] bytes = IOUtils.toByteArray(inputPart.getBody(InputStream.class, null));//IOUtils来自commons.io
log.info("上传文件字节大小:" + bytes.length);
File desti = new File(makeFilePath(typeCode, year, month, header));
while(desti.exists()){
desti = new File(makeFilePath(typeCode, year, month, header));
}
//来自commons.io包
FileUtils.writeByteArrayToFile(desti, bytes);
//虚拟路径
sb.append("/img/" + typeCode + "/" + year + "/"
+ (month < 10 ? ("0" + month) : month)
+ "/temp/" + desti.getCanonicalPath()
.substring(desti.getCanonicalPath().lastIndexOf("\\") + 1));
if(i != imageNum - 1){
sb.append(',');
}
} catch (IOException e) {
e.printStackTrace();
log.error("上传文件失败!");
return "-1";
}
}
}
log.info("成功上传图片!");
log.info("上传成功后返回图片的路径:" + sb.toString());
return sb.toString();
}