FileUitl.java文本操作工具类
/**
* 读取数据流生成图片
* @param imageIo
* @param path
* @return
*/
public boolean base64ToImage(String imageIo, String path){
boolean imageFlag = false;
FileOutputStream fileOutputStream = null;
try {
//把加密的图片流解密成字符
byte[] faceBytes = Base64.decodeBase64(imageIo);
// 生成图片
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fileOutputStream = new FileOutputStream(path);
IOUtils.write(faceBytes, fileOutputStream);
imageFlag = true;
} catch (IOException e) {
logger.error("图片保存写入失败");
e.printStackTrace();
} finally {
IOUtils.closeQuietly(fileOutputStream);
}
return imageFlag;
}
controller业务
/**
* 上传手持身份证照片
* @param requests
* @param response
* @return
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public BaseResult upload(MultipartHttpServletRequest requests, HttpServletResponse response){
BaseResult baseResult = new BaseResult();
Iterator<String> itr = requests.getFileNames();
MultipartFile mpf = null;
//上传路径
String typeUrl="selfie/";
String str=dateUtil.dateToYYMMDD(new Date()).replace("-","");
String month=str.substring(0,6);
String day=str.substring(6);
//String type="/fronts/images/";
while(itr.hasNext()){
mpf = requests.getFile(itr.next());
String url=IMG_BASE_PATH+typeUrl+month+"/"+day+"/"+mpf.getOriginalFilename();
try {
//FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(url));
// 生成图片
BASE64Encoder encoder = new BASE64Encoder();
String image=encoder.encode(mpf.getBytes());
boolean imageFlag = fileUtil.base64ToImage(image, url);
if(!imageFlag){
baseResult.setCode(GlobalCodeEnum.CODE_500.getKey());
baseResult.setMessage("转换成图片/保存下来失败");
logger.info("转换成图片/保存下来失败 type:{}", typeUrl);
return baseResult;
}
baseResult.setMessage("上传成功");
baseResult.setData(url);
baseResult.setSuccess(true);
} catch (IOException e) {
baseResult.setSuccess(false);
baseResult.setMessage("上传失败");
}
}
return baseResult;
}
html页面
前端input控件需这样写:
<input class="upload" id="file" type="file" name="file" accept="image/*" capture="camera"/>
$('#file').fileupload({
url:"/front/attach/upload",
autoUpload: true,
dataType: 'json',
maxFileSize: 10485760,
add:function (e,data) {
$.each(data.files,function (index) {
var reg = /gif|jpe?g|png/;
var type = $(this)[index].type;
var s = type.replace('image/',"");
var size = $(this)[index].size;
if (reg.test(s)&&size<10485760){
data.submit();
}else {
layer.msg('您选择的图片类型不对或者图片超过10MB,请重新选择', {time : 2000}, function(){});
}
})
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.progress').show().children('.bar').width(progress+'%')
if (progress==100){
setTimeout(function () {
$('.progress').hide();
},1000)
}
},
done: function (e, data) {
console.log(data)
if (data.result.success) {
$('.attach-box .attact-upload .upload-img').hide();
$('.attach-box .attact-upload .up-font').hide();
//回显操作
var path="/front/attach/downloadMaterialInfo?path="+data.result.data;
$('#target').attr('src',path).show();
$("#photo").val(data.result.data);
$('.reupload').show();
layer.msg(data.result.message, {time : 3500}, function(){});
} else{
layer.msg(data.result.message, {time : 3500}, function(){});
}
},
fail:function (e, data) {
layer.msg("系统错误", {time : 3500}, function(){});
}
})
从服务器下载文件controller
/**
* 附件下载
* @param path
* @param request
* @param response
* @throws IOException
*/
@RequestMapping("/downloadMaterialInfo")
public void downloadMaterialInfo(String path, HttpServletRequest request, HttpServletResponse response) throws IOException {
InputStream photoInputStream = null;
OutputStream outputStream = null;
try {
if (path == null) {
//path = request.getSession().getServletContext().getRealPath("/images/unupload.jpg");
path = getClass().getResource("/static/images/unupload.jpg").getFile();
}
File downloadFile = null;
if (path == null || !(downloadFile = new File(path)).exists()) {
//path = request.getSession().getServletContext().getRealPath("/images/notFoundImg.png");
path = getClass().getResource("/static/images/notFoundImg.png").getFile();
downloadFile = new File(path);
}
int length = (int) downloadFile.length();
String fileName = URLEncoder.encode(downloadFile.getName(), "UTF-8");
response.reset();
response.setContentLength(length);
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
photoInputStream = new FileInputStream(downloadFile);
outputStream = response.getOutputStream();
IOUtils.copyLarge(photoInputStream, outputStream);
} catch (IOException e) {
throw e;
} finally {
IOUtils.closeQuietly(outputStream);
IOUtils.closeQuietly(photoInputStream);
}
}