附件上传前端部分:
<div>上传:<input type="file" name="file" id="file" keys=""></div>
$("#file").change(function (e) {
var file = e.target.files[0] || e.dataTransfer.files[0];
console.log(file);
var key1 = $("#file").attr("keys");
if(key1==undefined){
key1="";
}
if (file) {
var formData = new FormData();
formData.append("file", file);
formData.append("key1", key1);
$.ajax({
url: 'toImgKey',
type: 'post',
data: formData,
cache: false,
processData: false,
contentType: false,
dataType: 'json',
mimeType: "multipart/form-data",
}).success(function (res) {
if(res==1){
parent.layer.msg("未上传附件");
}else if(res==2){
parent.layer.msg("附件类型不符合");
}else if(res==3){
parent.layer.msg("附件转换base64异常");
}else if(res==4){
parent.layer.msg("写入异常");
}else if(res==5){
parent.layer.msg("流程服务异常");
}else {
$("#file").attr("keys",res);
parent.layer.msg("成功");
}
})
}
});
后台部分:
/**功能描述
* @Desc
* @Description
* @Author
* @Date Created in 11:31 2019/2/25
* @Params
* @return 1未上传附件 2附件类型不符合 3附件转换base64异常 4写入MongoDB异常 5流程服务异常
* @Version:
*
*
*/
@ResponseBody
@RequestMapping(value = "/toImgKey",method = RequestMethod.POST)
public String toImgKey(MultipartFile file,String key1){
String base64;
String key;
//获取附件信息
try {
//判读当前系统
//读取配置文件
if(file==null) {
log.info("未上传附件");
return "1";
// 判断是否为空文件
}else if (file.isEmpty()) {
log.info("未上传附件");
return "1";
}else {
String fileName = file.getOriginalFilename();
if(fileName.endsWith(".jpg") || fileName.endsWith(".png")){
InputStream in =file.getInputStream();
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
copy(in,byteArrayOutputStream);
byte []img =byteArrayOutputStream.toByteArray();
base64=Base64.encode(img);
}else {
log.info("附件类型不符合");
return "2";
}
}
}catch (Exception e){
e.printStackTrace();
log.info("流程服务异常");
return "5";
}
}