1.第一步前端上传文件以及表单,filebox_file_id_1是input的id var formData = new FormData(); formData.append("files", $("#filebox_file_id_1")[0].files[0]); var form = $('#ff').serializeObject(); formData.append("content",form.content); formData.append("title",form.title); formData.append("rank1",form.rank1); formData.append("id",form.id); $.ajax({ url: '${request.contextPath}/app/repairskills/save', type: 'post', data: formData, contentType:false, processData:false, dataType:"json", mimeType:"multipart/form-data", success: function(res) { if (res.code == 0) { $('#dlg').dialog('close'); reload(); } else if(res.code == -99){ location.href = '${request.contextPath}/login'; }else { alert(res.msg); } }, error: function(res) { alert("操作失败"); } });
2.java接受并存储
@PostMapping("/save") public R save(RepairSkillsEntity repairSkills, @RequestParam( value="files",required=false)MultipartFile file)throws Exception{ if (file != null) { repairSkills.setImg(file.getBytes()); } repairSkillsService.save(repairSkills); return Result.ok(); }
实体类
public class RepairSkillsEntity implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String content; private String title; private byte[] img; private Integer rank1; }
3.前端展示
img为返回前端的实体类中的img,
{
"id":8,
"content":"1",
"title":"1",
"img":"iVBORw0KGgoAAAANSUhEUgAAASgAAAGRCAIAAABZoLnzAAAoVUlEQVR4Xu2djXcUt7nG++",
"rank1":2
}
<img src='data:image/png;base64," + img+ "' style='width:100px;height:100px'>
来源:CSDN
作者:汽水猫
链接:https://blog.csdn.net/f1370335844/article/details/104592441