java图片服务器/上传图片到服务器返回URL

后端代码: 

/**
     * 文件上传返回url
     */
    @ResponseBody
    @RequestMapping("/upload")
    public String uploadPicture(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        File targetFile=null;
        String url="";//返回存储路径
        int code=1;
        System.out.println(file);
        String fileName=file.getOriginalFilename();//获取文件名加后缀
        if(fileName!=null&&fileName!=""){
            String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/imgs/";//存储路径
            String path = request.getSession().getServletContext().getRealPath("upload/imgs"); //文件存储位置
            String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
            fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名

            //先判断文件是否存在
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileAdd = sdf.format(new Date());
            //获取文件夹路径
            File file1 =new File(path+"/"+fileAdd);
            //如果文件夹不存在则创建
            if(!file1 .exists()  && !file1 .isDirectory()){
                file1 .mkdir();
            }
            //将图片存入文件夹
            targetFile = new File(file1, fileName);
            try {
                //将上传的文件写到服务器上指定的文件。
                file.transferTo(targetFile);
                url=returnUrl+fileAdd+"/"+fileName;
                map.put("url", url);
                map.put("fileName", fileName);
                return Result.toResult(ResultCode.SUCCESS, map);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.toResult(ResultCode.SYSTEM_INNER_ERROR);
            }
        }
        return Result.toResult(ResultCode.SYSTEM_INNER_ERROR);
    }

注:本地需手动新建/upload/imgs文件夹

前端代码:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <label class="col-sm-2 control-label">请选择要上传的图片:</label>
        <div class="col-sm-10">
        <input type="hidden" name="img"  id="photoUrl"/>
        <input type="file" name="logoFile" id="logoFile" onchange="setImg(this);"><br>
        <span><img id="photourlShow" src="" width="500" height="500"/></span><br>
        <span><input id="show" style="width: 500px"></span>
        </div>
</body>
</html>
<script src="/jquery.min.js"></script>
<script type="text/javascript">

    function setImg(obj){
        var f=$(obj).val();
        if(f == null || f ==undefined || f == ''){
            return false;
        }
        if(!/\.(?:png|jpg|bmp|gif|PNG|JPG|BMP|GIF)$/.test(f))
        {
            alert("类型必须是图片(.png|jpg|bmp|gif|PNG|JPG|BMP|GIF)");
            $(obj).val('');
            return false;
        }
        var data = new FormData();
        console.log(data);
        $.each($(obj)[0].files,function(i,file){
            data.append('file', file);
        });
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/upload",
            data: data,
            cache: false,
            contentType: false,    //不可缺
            processData: false,    //不可缺
            dataType:"json",
            success: function(ret) {
                console.log(ret);
                if(ret.code==10000){
                    $("#photoUrl").val(ret.data.url);//将地址存储好
                    $("#photourlShow").attr("src",ret.data.url);//显示图片
                    $("#show").attr("value",ret.data.url);//显示图片
                    alert(ret.msg);
                }else{
                    alertError(ret.msg);
                    $("#url").val("");
                    $(obj).val('');
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("上传失败,请检查网络后重试");
            }
        });
    }
</script>
</html>

此时项目完成。

================================================================================================

当打包为jar包时,文件是保存在服务器中的。由于对于linux服务器来说,是不可以直接读取系统文件的。

所有在此需手动创建一个文件流来读取图片显示出来。

/**
     *author:zhaohe
     * IO流读取图片
     * @param imgUrl 图片url
     */
@RequestMapping(value = "/showImg",method = RequestMethod.GET)
public void IoReadImage(String imgUrl, HttpServletResponse response)throws IOException {
    fileService.IoReadImage(imgUrl,response);
}

private String GOODS_IMG_PATH = "/home/installPackage/imgs/";

public void IoReadImage(String imgUrl, HttpServletResponse response) throws IOException {
        ServletOutputStream out = null;
        FileInputStream ips = null;
        String upload = null;

        try {
            //获取图片存放路径
            String imgPath = GOODS_IMG_PATH + "/" + imgUrl;
            ips = new FileInputStream(new File(imgPath));
            String type = imgUrl.substring(imgUrl.indexOf(".")+1);
            if (type.equals("png")){
                response.setContentType("image/png");
            }
            if (type.equals("jpeg")){
                response.setContentType("image/jpeg");
            }
            out = response.getOutputStream();
            //读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1){
                out.write(buffer,0,len);
            }
            out.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            out.close();
            ips.close();
        }
    }

猜你喜欢

转载自blog.csdn.net/zgsdzczh/article/details/89350740