通用前端文件上传
//html代码
<div class="box">
<div class="research-smallTit" style="margin-top: 0;">
<h3>上传资料</h3>
</div>
<div class="type-group">
<div class="type-area" style="display: block;">
<div class="smaller-tex" style="">上传资料<i style="font-style: normal;color: #DE2222;">*</i></div>
<div class="choise-group">
<div class="smaller-tex">已添加资料</div>
<div class="choise-main addData-group">
</div>
</div>
<div class="research-btn" style="margin-top: 20px;">
<div class="btn-area" style="background: #3873BB;position: relative;">
<i class="layui-icon layui-icon-addition"></i>
<span>添加资料</span>
<input type="file" class="addData" multiple="">
</div>
</div>
</div>
</div>
<div class="research-btn" style="justify-content: center;display: flex;">
<div class="btn-area confirm-save-upload" style="background: #3873BB;">
<i class="layui-icon layui-icon-ok"></i>
<span>确认保存</span>
</div>
<div class="btn-area overview-back" style="background: #eee;">
<i class="layui-icon layui-icon-close" style="color: #666;"></i>
<span style="color: #666;">取消</span>
</div>
</div>
</div>
$(".addData").change(function () {
selectImg(this);
})
var uploaded_arr = [];
function selectImg(pic) {
if (!pic.files) {
return;
}
console.log(pic.files);
for (var i = 0; i < pic.files.length; i++) {
var po = pic.files[i];
console.log(pic.files[i], '***');
var forData = new FormData();
forData.set("file", po);
$.ajax({
xhrFields: {
withCredentials: true
},
type: "POST",
url: httpurl + "ldpMaterial/uploadFile",
data: forData,
dataType: "json",
processData: false,
contentType: false,
async: false,
success: function (res) {
console.log(res);
if (res.status == 1) {
uploaded_arr.push({
'FILE_NAME': res.file_name,
'FILE_TYPE': res.file_type,
'FILE_PATH': res.url,
'TRUE_NAME': res.true_name,
});
var name = res.true_name;
var ext_img = '';
if (res.file_type == 'pdf') {
ext_img = '<img src="../../../assets/images/fileTypeImg/icon4.png" alt="">';
} else if (res.file_type == 'pptx' || res.file_type == 'ppt') {
ext_img = '<img src="../../../assets/images/fileTypeImg/icon5.png" alt="">';
} else if (res.file_type == 'xlsx' || res.file_type == 'xls') {
ext_img = '<img src="../../../assets/images/fileTypeImg/xls.png" alt="">';
} else if (res.file_type == 'doc' || res.file_type == 'docx') {
ext_img = '<img src="../../../assets/images/fileTypeImg/doc.png" alt="">';
} else if (res.file_type == 'jpg' || res.file_type == 'png' || res.file_type == 'jpeg') {
ext_img = '<img src="../../../assets/images/fileTypeImg/img.png" alt="">';
} else {
ext_img = '<img src="../../../assets/images/fileTypeImg/icon8.png" alt="">';
}
$(".addData-group").append(`<div class="choise-area">
<div class="choise-area-left">
${ext_img}
<span>${name}</span>
</div>
<div class="choise-del" οnclick="del_div(this)">
<i class="layui-icon layui-icon-delete"></i>
<span>删除</span>
</div>
</div>`);
} else {
layer.alert("网络异常,请稍后再试");
}
},
error: function (res) {
layer.alert("网络异常,请稍后再试");
}
});
}
};
$(".confirm-save-upload").click(function () {
saveMaterial(uploaded_arr);
});
function saveMaterial(data) {
console.log(data);
if (data == null || data == "" || data == '' || data == []) {
layer.msg("请添加资料")
setTimeout(function () {
return false;
}, 2000)
} else {
$.ajax({
xhrFields: {
withCredentials: true
},
type: 'POST',
url: '',
data: {DATA: JSON.stringify(data)},
dataType: "json",
async: false,
success: function (res) {
layer.alert(res.msg, function (msg) {
layer.close(msg);
if (res.status == 1) {
window.parent.location.reload();
}
});
},
error: function (res) {
layer.close(loading);
layer.alert("网络异常,请稍后再试");
}
});
}
}
function del_div(dom) {
var index = $(dom).parent().index();
$('.choise-area').eq(index).remove();
uploaded_arr.splice(index, 1);
}
@RequestMapping("/uploadFile")
@ResponseBody
public Object uploadFile(@RequestParam(value = "file", required = false) MultipartFile[] file) {
Map<String, Object> map = new HashMap<>();
String filePath = Const.IMAGE;
String name = file[0].getOriginalFilename();
String fileName = FileUpload.fileUp(file[0], filePath, UuidUtil.get32UUID());
map.put("url", "/file/" + fileName);
map.put("status", '1');
if (!"".equals(fileName) && fileName != null) {
map.put("file_name", fileName);
map.put("true_name", name);
map.put("file_type", fileName.split("\\.")[1]);
}
map.put("msg", "上传成功!");
return map;
}
上传公共类
package org.fh.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
public class FileUpload {
public static String fileUp(MultipartFile file, String filePath, String fileName){
String extName = "";
try {
if (file.getOriginalFilename().lastIndexOf(".") >= 0){
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
}
copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
} catch (IOException e) {
System.out.println(e);
}
return fileName+extName;
}
public static String copyFile(InputStream in, String dir, String realName)
throws IOException {
File file = mkdirsMy(dir,realName);
FileUtils.copyInputStreamToFile(in, file);
in.close();
return realName;
}
public static File mkdirsMy(String dir, String realName) throws IOException{
File file = new File(dir, realName);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
return file;
}
public static String getHtmlPicture(String httpUrl, String filePath , String myFileName) {
URL url;
BufferedInputStream in;
FileOutputStream file;
try {
String fileName = null == myFileName?httpUrl.substring(httpUrl.lastIndexOf("/")).replace("/", ""):myFileName;
url = new URL(httpUrl);
in = new BufferedInputStream(url.openStream());
file = new FileOutputStream(mkdirsMy(filePath,fileName));
int t;
while ((t = in.read()) != -1) {
file.write(t);
}
file.close();
in.close();
return fileName;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}