图片在页面上的写入和读取(框架:freemarker+mybatis+mysql)

1,首先保存商品图片,不要忘记以多媒体文件提交:enctype="multipart/form-data"

前台页面, freemarker中:

<p style="width: auto;">
                    <label style="margin-left:140px; margin-top: 8px;" style="width:60px;">商品图片</label>
</p>
 <p style="width:430px;margin-top:8px;">
                <label style="margin-left: 1px; color:green;font-size:16px;width:150px;">选择jpg或者png:</label>
 <input type="file" id="file" name="file" onchange="getFilePath(),preImg(this.id,'imgPre')" style="filter:alpha(opacity=0);opacity:0;width: 0;height: 0;"/> 
               <input id="excelid" type="text" name="picture" value="${(commodity.picture)!}" class='txt' readonly="readonly"/>  
    <input style="margin-left:6px; cursor: pointer;" id="btn" type='button' name="file" class='btn' value='浏览...' onclick="selectFile();"/>
   <img id="imgPre" src="${projectName}/?spm=${encryption("Commodity/ShowImg")}&id=${(commodity.comm_no)!}" width="140px" height="120px" style="margin-top: 8px; display: block;" /> 
 </p>

 

 js校验图片:

<script type="text/javascript">
$(function(){
    $("#file").change(function(){
        $("#noChoice").css("display","none");
        var filePath=$(this).val();
        var suffix = filePath.substring(filePath.lastIndexOf('.'));
        if(suffix != '.jpg' && suffix != '.png' && suffix != '.PNG' && suffix != '.JPG'){
            alertMsg.info('请重新选择.jpg或png文件!');
        }else{
            $("#noChoice").css("display","inline");
        }
    });
});
function selectFile(){  
    //触发 文件选择的click事件  
    $("#file").trigger("click");  
    //其他code如 alert($("#file").attr("value"))  
}  
/* 获取 文件的路径 ,用于测试*/  
function getFilePath(){  
    $("#excelid").val($("#file").attr("value"));
}
//显示本地图片
function getFileUrl(sourceId) {   
    var url;   
    if (navigator.userAgent.indexOf("MSIE")>=1) { // IE   
    url = document.getElementById(sourceId).value;   
    }   
    else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox   
    url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));   
    }   
    else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome   
    url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));   
    }   
    return url;   
}  
function preImg(sourceId, targetId) {   
    var url = getFileUrl(sourceId);   
    var imgPre = document.getElementById(targetId);   
    imgPre.src = url;
}  

</script>

 

后台:

/**
     * ********************************************************
     * @Title: save
     * @Description: 修改保存
     * @return String
     * @throws IOException 
     * @date 2018-05-09 下午 03:02:58 
     ********************************************************
     */
     @RequestMapping("/save")
    public @ResponseBody Map save(@RequestParam(required = false) MultipartFile file,@ModelAttribute("Commodity") Commodity  commodity) throws IOException{
         if(file.getSize()>0){
             String picName = System.currentTimeMillis()+"."+file.getOriginalFilename().split("\\.")[1];
             String picUrlPath = DateUtil.getTypeUrl("commondata", "commpicpath");
             String picUrlPathd = DateUtil.getTypeUrl("commondata", "commpicpath")+"//"+picName;
             //判断文件夹是否存在,不存在则创建新文件夹
             File picFile = new File(picUrlPath);
             if (!picFile.isDirectory()) { // 目录不存在          
                 picFile.mkdir(); // 创建目录
             }
             //1,创建目标图片文件
             File descPic = new File(picUrlPathd);
             // 2.提供相应的流对象
             FileInputStream fis = null;
             FileOutputStream fos = null;
             try {
                 fis = (FileInputStream) file.getInputStream();
                 fos = new FileOutputStream(descPic);
                 // 3.实现复制
                 byte[] byts = new byte[1024];
                 int len;
                 while ((len = fis.read(byts, 0, byts.length)) != -1) {
                     fos.write(byts, 0, len);
                 }
             } catch (Exception e) {
                 e.printStackTrace();
             }finally{
                 fis.close();
                 fos.close();
             }
             commodity.setPicture(picName);
         }
         if(commodity.getComm_no()==null||commodity.getComm_no().equals("")){
             resForFinally=commodityService.insert(commodity);
         }else{
             resForFinally=commodityService.update(commodity);
         }
         message = resForFinally > 0 ? "保存成功" : "保存失败";
         return message2(message,resForFinally);
    }

 

读取配置文件的工具类:

  /**
     * 
     *********************************************************.<br>
     * [方法] getProperty <br>
     * [描述] TODO(根据服务器类型取不同地址) <br>
     * [参数] TODO(文件名,路径key) <br>
     * [返回] String <br>
     * [时间] 2018-2-8 上午10:58:29 <br>
     * [作者] 郭太东 【lc】
     *********************************************************.<br>
     */
    public static String getTypeUrl(String name, String url){
        ResourceBundle rb=ResourceBundle.getBundle(name);
        String reurl = rb.getString("server")+url;
        return rb.getString(reurl);
    }

 

配置文件:(文件名:commondata.properties,位于项目根目录下 )

#linux, windows  \u5F53\u524D\u7C7B\u578B

server=windows

#\u672C\u5730
#\u5546\u54C1\u56FE\u7247\u4E0A\u4F20\u8DEF\u5F84
windowscommpicpath=E\://YGZC//commimportPicture
#\u663E\u793A\u5546\u54C1\u56FE\u7247\u7684\u8DEF\u5F84
picturePath=E\:\\YGZC\\commimportPicture\\
img.root=E\://YGZC//commimportPicture

以上为商品tu'p图片的添加,ru'g如果要修改商品,则需要对商品进行读取显示,下面是对商品图片在修改的进行回显的代码:

/**
     * ********************************************************
     * @Title: ShowImg
     * @Description:显示商品图片   
     * @return String
     * @date 2018-05-17 下午 05:28:15 
     ********************************************************
     */
    @RequestMapping(value="ShowImg")
    public void ShowImg(HttpServletRequest request,HttpServletResponse response) throws IOException{
       String id = request.getParameter("id"); //文件名
       if(id!=null&&!id.equals("")){
           //E:\YGZC\commimportPicture\1526550721498.jpg
           String path= commodityService.getString("getPicurl", id).toString();

          //这里是存放图片的文件夹地址
           String picUrlPathd = DateUtil.getUrl("commondata", "picturePath")+path;
           System.out.println(picUrlPathd);
           FileInputStream fileIs=null;
           try {
                 fileIs = new FileInputStream(picUrlPathd);
               } catch (Exception e) {
                 return;
               }
                   int i=fileIs.available(); //得到文件大小   
                   byte data[]=new byte[i];   
                   fileIs.read(data);  //读数据   
                   response.setContentType("image/*"); //设置返回的文件类型   
                   OutputStream outStream=response.getOutputStream(); //得到向客户端输出二进制数据的对象   
                   outStream.write(data);  //输出数据      
                   outStream.flush();  
                   outStream.close();   
                   fileIs.close();  
             
       }
    }