JS
upload.render({
elem: '#test3'
,url: '/meetingReport/upload' //改成您自己的上传接口
,accept: 'file' //普通文件
,done: function(res){
//h回掉方法不用看
if(res.flag){
layer.msg('上传成功');
$('#uploadUrl1').val(res.files.fileUrl);
$('#uploadName1').html(res.files.fileName);
// $('#uploadName1').attr('href',res.files.fileUrl);
$('#uploadName1').click(function () {
window.open(res.files.fileUrl)
});
// $('#upload1').show();
}
}
});
JAVA Controller 层
/**
* 主题附件上传
* @param file
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public JSONObject upload(@RequestParam MultipartFile file, HttpServletRequest request) throws Exception {
// 生成多个InputStream(为了第二次保存前来传来的file)
InputStream is = file.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > -1) {
baos.write(buffer, 0, length);
}
baos.flush();
//生成文件2 (这里前台传来的文件需要保存两次 target中一次 本地项目中一次 为了实现立马可以拿到上传的文件)
InputStream stream2 = new ByteArrayInputStream(baos.toByteArray());
MultipartFile file2 = new MockMultipartFile(file.getName(), stream2);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = sdf.format(new Date()) + new Random().nextInt(99)+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
// String fileName = file.getOriginalFilename();
//System.getProperty("user.dir") 获取项目本地绝对路径 然后拼接 项目包路径 和编译好的 target路径(存放文档的文件夹一定要在static底下 要不拿不到)
String path = System.getProperty("user.dir")+"/src/main/resources/static/file/";
String targetPath = System.getProperty("user.dir")+"/target/classes/static/file/";
String name = FileUtil.uploadFile1(file, path, fileName);
FileUtil.uploadFile1(file2, targetPath, fileName);
// String host = IPUtils.getIpAddr(request);
//文件相对路径
String webUrl =
// host + ":" + port +
"/file/" + name;
JSONObject jsonObject = new JSONObject();
JSONObject json = new JSONObject();
json.put("fileUrl", webUrl);
json.put("fileName", name);
jsonObject.put("files", json);
if(!Tools.isEmpty(name)){
jsonObject.put("flag", true);
}
return jsonObject;
}
uploadFile1
public static String uploadFile1(MultipartFile file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath+fileName);
/*
* if (!targetFile.exists()) { targetFile.mkdirs(); }
*/
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdir();
}
// if (!targetFile.exists()) {
// targetFile.createNewFile();
// }
// System.out.println("asda: " + filePath);
file.transferTo(targetFile); // 保存文件
return fileName;
}
MockMultipartFile 需要用到spring-test的 maven包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>