java 上传图片文件并在页面的显示功能
程序员文章站
2022-05-14 22:21:35
...
具体思路
1.图片前端通过异步请求上传后端
1.1 img 标签和上传文件按钮(样式使用bootstrap)
<form name="aform" id="aform">
<div style="width: 180px;height: 250px;">
<img id="img_" style="margin-bottom:5px;margin-left:11px; display:inline-block; width:206px;height:210px;border:1px solid black;" src="" alt="" />
<input type="file" style="margin-left: 10px;" class="" name = "imginfo" id="imginfo" value="请上传照片" οnchange="uploadimg();"/>
</div>
</form>
1.2 上传按钮的触发事件(js块)
function uploadimg(){
var form = new FormData(document.getElementById("aform"));
$.ajax({
url:"${_path}/demo/uploadimg",
type:"post",
data:form,
processData:false,
contentType:false,
success:function(data){
if (data.res=='ok') {
$('#img_').attr("src","data:image/png;base64,"+ data.base64);
}
}
});
}
2.后端解析图片内容转化为base64编码返回给页面
/*
可能需要的包
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
*/
@ResponseBody
@RequestMapping(value = "uploadimg",method = RequestMethod.POST)
public Map<String, Object> uploadimg(@RequestParam("imginfo") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
Map<String, Object> _out = new HashMap<>();
if (!file.isEmpty()) {
DiskFileItem diskFileItem = (DiskFileItem)file.getFileItem();
File uploadfile= diskFileItem.getStoreLocation();
String base64 = null;
InputStream in = null;
try {
in = new FileInputStream(uploadfile);
byte[] bytes=new byte[(int)uploadfile.length()];
in.read(bytes);
base64 = Base64Utils.encodeToString(bytes);
_out.put("res","OK");
//返回的base64编码 通过前台解析放入页面的img标签
//也可以在此写数据库代码 将img写入数据库
_out.put("base64",base64);
if (msg.split("[|]")[0].equals("0")) {
_out.put("res", "ok");
_out.put("base64", base64);
} else {
_out.put("res", msg.split("[|]")[1]);
}
} catch (Exception e) {
e.printStackTrace();
_out.put("res", e.getMessage());
}finally {
in.close();
}
}
return _out;
}
}
return ret;
}
上一篇: 页面实现复制功能
下一篇: jsp 页面的基本部署