javaWeb中,easyui实现图片的上传,并将其路径保存到数据库中

1.html中的代码:

    Note: 记得设置form的 enctype="multipart/form-data"

    <div id="tb">
        <form id="fm" method="post" enctype="multipart/form-data">
            <input style="width: 180px;" id="assetphotourl" type="file" name="assetphotourl" multiple/>
            <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="AssetPhotosAdd($('#assetnum1').val())">添加</a>
        </form>
    </div>

2.js代码:

      Note:如果文件不为空则将form表单提交。

function AssetPhotosAdd(assetnum) {
    var files = document.getElementById("assetphotourl").files;
    var length = files.length;
    if(length != 0){
        $("#fm5").form("submit", {
            type:"post",  //提交方式
            url:getRealPath()+'/AssetPhotos/assetPhotosUpload/'+assetnum, //请求url
            success:function(data)
            { //提交成功的回调函数
                $.messager.alert("提示","附件上传成功","info");
            },
            error:function () {
                $.messager.alert("提示","附件上传失败","info");
            }
        });
    }
}

3.所请求的Controller层代码:

    @ResponseBody
    @RequestMapping("/assetPhotosUpload/{assetnum}")
    /**
     * @Description  :资产附件上传功能
     * @author       : bjh
     * @param        : [assetnum, assetphotourl, request]
     * @return       : java.lang.Boolean
     * @exception    :
     * @date         : 2018/8/11 9:57
     */
    public Boolean assetPhotosUpload(@PathVariable("assetnum") String assetnum,
                                     @RequestParam(value ="assetphotourl", required = false) CommonsMultipartFile[]  assetphotourl,
                                     HttpServletRequest request) {

        if(assetphotourl == null){
            return false;
        }
        //上传文件保存位置
        String pathString =  request.getSession().getServletContext().getRealPath("/View/Resourse/AssetPhotos");
        //判断文件夹是否存在
        File file=new File(pathString);
        if(!file.exists() && !file.isDirectory()) {
            //创建文件夹
            file.mkdirs();
        }
        //批量上传
        for(int i = 0;i<assetphotourl.length;i++) {
            if(!assetphotourl[i].getOriginalFilename().isEmpty()){//获取文件名
                //避免出现重复文件名,采用UUID生成随机文件名
                String fileName = assetphotourl[i].getOriginalFilename();
                int indexOf = fileName.lastIndexOf(".");
                String substring = fileName.substring(indexOf);
                String path = pathString+"\\"+ UUID.randomUUID().toString().replaceAll("-","")+substring;
                File newFile=new File(path);
                try {
                    //上传资产附件图片
                    assetphotourl[i].transferTo(newFile);
                    assetPhotosService.assetPhotosAdd(assetnum,path);
                } catch (IllegalStateException | IOException e) {
                    e.printStackTrace();
                }
            }else if(assetphotourl.length == 1) {
                return false;
            }
        }
        //返回上传成功
        return true;
    }

4.Service中的代码:

    @Override
    /**
     * @Description  :将资产附件进行添加
     * @author       : bjh
     * @param        : [assetnum, path]
     * @return       : void
     * @exception    :
     * @date         : 2018/8/11 9:57
     */
    public void assetPhotosAdd(String assetnum, String path) {
        int index = path.indexOf("\\View\\Resourse\\AssetPhotos");
        String assetPhotosURL = path.substring(index);
        assetPhotosDao.assetPhotosAdd(assetnum, assetPhotosURL);
    }

5.Dao层代码:(采用Hibernate框架)

    @Override
    /**
     * @Description  :资产附件的添加
     * @author       : bjh
     * @param        : [assetnum, assetPhotosURL]
     * @return       : void
     * @exception    :
     * @date         : 2018/8/11 10:06
     */
    public void assetPhotosAdd(String assetnum, String assetPhotosURL) {
        Session session = getSession();
        Transaction tx = session.beginTransaction();
        try{
            Assetphotos assetphotos = new Assetphotos();
            assetphotos.setAssetnum(assetnum);
            assetphotos.setAssetphotourl(assetPhotosURL);
            assetphotos.setAssetphotoremarks("无");
            session.save(assetphotos);
            tx.commit();
        }catch (Exception e){
            tx.rollback();
            e.printStackTrace();
        }finally {
            close(session);
        }
    }

6.图片上传成功,且成功将其在服务器端的路径保存到了数据库中。

实现图片地址上传数据库并从数据库获取地址进行显示,你可以按照以下步骤进行操作: 1. 创建数据库表,用于存储图片信息,表结构可以包含图片ID,图片名称,图片路径等字段。 2. 在前端页面,使用表单上传图片,然后将图片保存到服务器指定目录,并获取到图片路径。 3. 在后端代码,将图片路径保存数据库,可以使用JDBC或者ORM框架进行数据库操作。 4. 在前端页面,通过后端接口从数据库获取图片路径,然后将图片显示在页面上。 以下是一个基于Spring MVC和MyBatis框架的示例代码,用于上传图片并将图片路径保存数据库: 前端页面: ``` <form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="Upload" /> </form> ``` 后端Controller: ``` @Controller public class UploadController { @Autowired private ImageService imageService; @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) { try { // 保存图片到服务器指定目录 String path = "D:/uploads/" + file.getOriginalFilename(); file.transferTo(new File(path)); // 将图片路径保存数据库 Image image = new Image(); image.setName(file.getOriginalFilename()); image.setPath(path); imageService.saveImage(image); } catch (IOException e) { e.printStackTrace(); } return "redirect:/"; } } ``` Service: ``` @Service public class ImageService { @Autowired private ImageMapper imageMapper; public void saveImage(Image image) { imageMapper.insert(image); } public Image getImageById(Long id) { return imageMapper.selectById(id); } } ``` Mapper: ``` @Mapper public interface ImageMapper { @Insert("insert into image (name, path) values (#{name}, #{path})") void insert(Image image); @Select("select * from image where id = #{id}") Image selectById(Long id); } ``` 最后,在前端页面,通过后端接口获取图片路径,并将图片显示在页面上: ``` <img src="/image?id=1" /> ``` Controller: ``` @Controller public class ImageController { @Autowired private ImageService imageService; @GetMapping("/image") public void getImage(@RequestParam("id") Long id, HttpServletResponse response) { Image image = imageService.getImageById(id); try { OutputStream out = response.getOutputStream(); FileInputStream in = new FileInputStream(new File(image.getPath())); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 这样就可以实现图片地址上传数据库并从数据库获取地址进行显示了。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值