一、multipartfile方式
html添加:
<link href="../static/css/plugins/fileinput/fileinput.min.css" rel="stylesheet">
<link href="../static/js/plugins/fancybox/jquery.fancybox.css" rel="stylesheet">
<script src="../static/js/plugins/fileinput/fileinput.min.js"></script>
<script src="../static/js/plugins/fileinput/zh.js"></script>
<td>
<form class="form-horizontal" enctype="multipart/form-data" method="post" id="uploadForm">
<input id="fileinput" name="file" multiple type="file" class="file-loading">
</form>
</td>
js initFileInput("fileinput", "/pic/imageUpload","1",false); //初始化fileinput控件(第一次初始化) var initFileInput = function(ctrlName, uploadUrl,fmax,fpreview) { var control = $('#' + ctrlName); $(document).on('ready', function () { control.fileinput({ language: 'zh', //设置语言 allowedFileExtensions: ['jpg', 'png', 'gif'],//接收的文件后缀 uploadUrl: uploadUrl, //上传的地址 maxFileCount: fmax,//表示允许同时上传的最大文件个数 enctype: 'multipart/form-data',//2进制传输数据 showUpload: true, //是否显示上传按钮 showRemove : false, //显示移除按钮 showCaption: true,//是否显示标题 showPreview: fpreview, //是否显示预览框 uploadAsync: true, //是否异步方式提交 dropZoneEnabled: fpreview,//是否显示拖拽区域 initialPreviewShowDelete:false, initialPreview:[], initialPreviewConfig:[], maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小 elErrorContainer: '#errorBlock' //错误信息显示地方 }); }); }; // 上传成功后处理 $('#fileinput').on('fileuploaded', function(event, data, previewId, index) { //加上传成功后的动作 });
controller
@RequestMapping("/pic/imageUpload")
@ResponseBody
public String imageUpload(MultipartFile file) {
String value = "/images";
String LocalhostUrl=PropertiesFactoryUtil.getProperties("META-INF/config.properties")
.getProperty("rootPath");
if(file==null){
LOGGER.error("文件名为空");
Map<String, String> map = new HashMap<>();
map.put("fileName", "");
//System.out.println(map);
return JSON.toJSONString(map);
}
String originalName = null;
String UrlName = null;
try {
if ((file != null && !file.isEmpty())) {
originalName = file.getOriginalFilename();// 获得原文件名+扩展名
}
Date date = new Date();
// String dateName = new SimpleDateFormat("yyyyMMddHHmmss")
// .format(date);
String uuid = UUID.randomUUID().toString();
String dateName = new SimpleDateFormat("/yyyy/MM/dd/").format(date);
int index = originalName.lastIndexOf(".");
String extendName = originalName.substring(index);//获取后缀名
File out = new File(LocalhostUrl + value + dateName
+ uuid+extendName);
out.getParentFile().mkdirs();//创建目录
file.transferTo(new File(LocalhostUrl + value + dateName
+ uuid+extendName)); // 文件上传(本地絕對路徑+bizecode+时间+uuid)
UrlName = dateName + uuid+extendName;
} catch (Exception e) {
LOGGER.error("上传失败");
e.printStackTrace();
}
Map<String, String> map = new HashMap<>();
map.put("fileName", UrlName);
//System.out.println(map);
return JSON.toJSONString(map);
}
二、base64
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.Base64Utils;
public static String getImageStr(String imgFile) { //imgFile为图片路径
if(StringUtils.isEmpty(imgFile)){
return null;
}
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
String encodeToString = Base64Utils.encodeToString(data);// 返回Base64编码过的字节数组字符串
return encodeToString;
}
// 对字节数组字符串进行Base64解码并生成图片
public static boolean GenerateImage(String imgStr, String imgFilePath) {
if (imgStr == null)
return false;
try {
byte[] bytes = Base64.decodeBase64(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0)
bytes[i] += 256;
}
FileOutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.close();
return true;
} catch (Exception e) {
return false;
}
}
转载于:https://blog.51cto.com/1385903/1861969