Java上传图片到服务器
HTML页面的标签
<div id="div_selectpic" align="right" style="width: 300px;font-size: 15px;"> (格式jpg、bmp、png大小100K内)选择图片 <input name="txtfiles" type="text" id="txtfiles" style="display: none"> <input type="file" name="file_pic" id="file_pic" onchange="DynamicPicStr(this,100,'imgid','txtfiles',290,190)" style="width: 70px;" class="easyui-linkbutton"> </div>
<div>
<img id="imgid" alt=""/>
</div>
上传照片的js方法
//新增时图片上传调用,uploadobj:页面传入的文件对象,limitfilessize:限定文件的大小 function DynamicPicStr(uploadobj, limitfilesize, divid, txtid, width, height) { var files = uploadobj.files[0]; var oFReader = new FileReader(); oFReader.readAsDataURL(files); var strurl="";//图片物理地址 var txtobj = $("#"+txtid+""); var objdivimg = $("#"+divid+""); var limitpictype = ["jpg", "bmp", "png"]; try { //console.info("图片大小:"+files.size); if (parseInt(files.size / 1024) > limitfilesize) { alert("图片大小超过规定大小,只能小于" + limitfilesize + "K"); txtobj.value = ""; return false; } var filename = files.name; if (filename != "" && filename != null) { var searchindex = filename.indexOf("."); var filetypename = filename.substring(searchindex + 1, filename.length); var pictypebool = false; for (var i = 0; i < limitpictype.length; i++) { if (limitpictype[i].toLowerCase() == filetypename.toLowerCase()) { pictypebool = true; break; } } if (!pictypebool) { alert("图片类型不符合要求,图片类型只能是jpg , bmp , png"); txtobj.value = ""; return false; } } } catch (e) { alert(e.name + ": " + e.message + ",判断图片类型、图片大小失败"); } oFReader.onloadend = function(oFRevent) { strurl = oFRevent.target.result; objdivimg.attr("src",strurl); txtobj.val(files); } //objdivimg.attr("src",oFReader.result); txtobj.val(files); console.info("图:"+strurl); objdivimg.attr("width",width); objdivimg.attr("height", height); upload(uploadobj); }
//文件上传的方法 function upload(file) { //let img = document.getElementById('img') let formData = new FormData() let temp = file.files[0] var strurl = getContextPathInfo() + "/LowZjblb/upload"; if(temp) { formData.append('file', temp) //img.src = window.URL.createObjectURL(temp) $.ajax({ url: strurl, type: "POST", data: formData, processData: false, // 告诉jQuery不要去处理发送的数据 contentType: false, // 告诉jQuery不要去设置Content-Type请求头 success: function(result) { $("#newzjzp").val(result.appenddata);//服务器保存的路径 //alert(result); } }) } }
java后端Controller接收的方法
/** * * @Title:图片上传返回路径 * @Description * @param MultipartFile,request * @return 服务器保存的图片地址url * @throws */ @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody @Log(module = "法证补领管理", operation = "添加") public OperationResult upload(@RequestParam("file") MultipartFile files,HttpServletRequest request) { OperationResult result = new OperationResult(OperationResultTypeEnum.ERROR, "增加记录失败"); String dicName="UpFile";//服务器上传文件夹名称 String newFileName=files.getOriginalFilename(); newFileName=newFileName.substring(0,newFileName.lastIndexOf(".")); String picurl = UploadFile.saveFile(files,newFileName,dicName, request); result.setResulttype(OperationResultTypeEnum.SUCCESS); result.setMsg("上传成功"); result.setAppenddata(picurl); return result; }
java后端负责保存图片的方法如下
public static String saveFile(MultipartFile filedata,String newFileName,String dicName, HttpServletRequest request) { // TODO Auto-generated method stub String pathval = request.getSession().getServletContext().getRealPath("/"); // 根据配置文件获取服务器图片存放路径 //String newFileName = String.valueOf(System.currentTimeMillis()); Calendar cale = null; cale = Calendar.getInstance(); String year = String.valueOf(cale.get(Calendar.YEAR)); String month = String.valueOf(cale.get(Calendar.MONTH) + 1); String saveFilePath = "UpFile/"+dicName+"/"+year+"/"+month+"/"; /* 构建文件目录 */ File fileDir = new File(pathval + saveFilePath); if (!fileDir.exists()) { fileDir.mkdirs(); } // 上传的文件名 String filename = filedata.getOriginalFilename(); // 文件的扩张名 String extensionName = filename.substring(filename.lastIndexOf(".") + 1); try { String imgPath = saveFilePath + newFileName + "." + extensionName; // System.out.println(pathval + imgPath);打印图片位置 FileOutputStream out = new FileOutputStream(pathval + imgPath); // 写入文件 out.write(filedata.getBytes()); out.flush(); out.close(); return imgPath; } catch (Exception e) { e.printStackTrace(); } return null; }