基于springboot的本地和oss图片上传

/**
     * 上传图片到本地
     */
    /**
 * 获取当前是否是windows系统
 * @return true代表为真
 */
public static boolean isWindows() {
    return System.getProperty("os.name").toLowerCase().contains("windows");
}
/**
 * 默认的上传文件路径
 * TODO 默认配置文件路径
 */
public final static String UPLOAD_PATH = isWindows() ? "C:/upload/" : "/usr/local/upload/";

/**上传图片接口**/
@RequestMapping(value = "/file/doUploadPic", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity doModifyHead(HttpServletRequest request) {
        // 转型为MultipartHttpRequest:
        MultipartFile file = null;
        ResultEntity resultEntity = new ResultEntity();
        try {
            if (request instanceof MultipartHttpServletRequest) {
                MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
                multipartHttpServletRequest.getFileNames();
                file = multipartHttpServletRequest.getFile("file");
            }
            if (file == null) {
                return fail("请选择图片");
            }
            //获取图片扩展名
            String originalFilename = file.getOriginalFilename();
            //获取文件后缀
            String extName = file.getOriginalFilename().substring(originalFilename.lastIndexOf(".") + 1);
            //定义新文件名
            String fileName = RandomUtil.simpleUUID() + "." + extName;
            //本地访问路径
            String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/static";//访问路径
            //文件存储位置
            String path = ToolString.UPLOAD_PATH;
            //获取文件夹路径
            File file1 =new File(path);
            //如果文件夹不存在则创建
            if(!file1.exists()  && !file1 .isDirectory()){
                file1 .mkdir();
            }
            //将图片存入文件夹
            File targetFile = new File(file1, fileName);
            file.transferTo(targetFile);
            //最后的图片访问路径
           String url=returnUrl+"/"+fileName;
            if (StringUtils.isNotBlank(url)) {
                resultEntity.setCode(ResultEntity.SUCCESS);
                resultEntity.setMessage("图片上传成功");
                Map data = new HashMap<>();
                data.put("imgUrl", url);
                System.out.println("图片地址 :" + url);
                log.info("图片地址 :" + url);
                resultEntity.setData(data);
            } else {
                return fail("上传失败!");
            }
        } catch (Exception e) {
            return fail("上传失败!");
        }
        return resultEntity;
    }
    
    /**配置类
     * 配置用于访问上传到本地的图片
     * @param registry
     */
    @Slf4j
	@Configuration
    public class AdminConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("file:///"+ ToolString.UPLOAD_PATH);//图片存储位置(c:/upload)
        super.addResourceHandlers(registry);
    }

通过ip访问图片

/**    oss上传
     * 文件上传接口
     */
    @ResponseBody
    @RequestMapping(value = "/s/file/upload", method = RequestMethod.POST)
    public ResultEntity fileUpload(MultipartFile file) throws Exception {
        ResultEntity resultEntity = new ResultEntity();
        resultEntity.setCode(ResultEntity.SUCCESS);

        //判断图片是否为空
        if (file.isEmpty()) {
            resultEntity.setCode(ResultEntity.FAIL);
            resultEntity.setMessage("图片为空");
            return resultEntity;
        }
        //上传到图片服务器
        try {
            //获取图片扩展名
            String originalFilename = file.getOriginalFilename();
            String extName = file.getOriginalFilename().substring(originalFilename.lastIndexOf(".") + 1);
            String fileName = RandomUtil.randomUUID() + "." + extName;
            String url = OSSClientUtils.uploadFile(file.getBytes(), "/upload/" + fileName);
            url = OSSClientUtils.ACCESS_BASE_PATH + "/" + url;
            resultEntity.setData(url);
            System.out.println("图片地址:" + url);
        } catch (Exception e) {
            e.printStackTrace();
            resultEntity.setCode(ResultEntity.FAIL);
            resultEntity.setMessage("图片上传失败");
        }

        return resultEntity;
    }
/**
     * oss上传工具类
     */
public class OSSClientUtils {
    private static final String ENDPOINT = "http://oss-cn-zhangjiakou.aliyuncs.com";
    private static final String ACCESSKEYID = "LTAI4FbvNFtcL6hYv";//填写自己的oss
    private static final String ACCESSKEYSECRET = "o0ZPmniI3M2QLx";
    private static final String BUCKETNAME =  "zjxls";
    private static final String BASE_PATH = "images";
    public static final String ACCESS_BASE_PATH = "http://zjxls.oss-cn-zhangjiakou.aliyuncs.com"; //访问前缀

    public static OSSClient getInstence(){
        OSSClient ossClient = new OSSClient(ENDPOINT,ACCESSKEYID,ACCESSKEYSECRET);
        ossClient.createBucket(BUCKETNAME);
        return ossClient;
    }

    /**
     * 通过httpclient 上传图片
     * @param imgFile 文件对象
     * @return 上传之后的图片路径
     */
    public static void doUpload(File imgFile, String filePath) throws Exception {
        OSSClient ossClient = getInstence();
        ossClient.putObject(BUCKETNAME,filePath,imgFile);
        ossClient.shutdown();
    }
    /**
     * 上传文件
     *
     * @param file_buff
     * @param filePath
     * @return
     */
    public static String uploadFile(final byte[] file_buff, final String filePath) {
        final String path = BASE_PATH + filePath;
        ossClient(o -> o.putObject(BUCKETNAME, path, new ByteArrayInputStream(file_buff)));
        return path;
    }
    private static void ossClient(Consumer consumer) {
        OSSClient ossClient = new OSSClient(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
        try {
            consumer.accept(ossClient);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败");
        } finally {
            // 关闭client
            ossClient.shutdown();
        }
    }
}
前端上传多张图片并预览,上传接口为上面的oss上传图片接口
            html

js //编辑初始化加载图片 var picList = $("#pic").val(); var picArray =[]; if (picList.indexOf(",") == -1){ picArray.push(picList); } else { picArray = picList.split(','); } for (var i=0; i"); $('#show'+i).attr('src',picArray[i]);//将图片的路径设置为返回上传的图片的地址 $("#show"+i).show();//将图片设置为可见 $("#del"+i).show();//将删除设置为可见 } //添加新图片 var i=0; function changepic(obj) { var str = $("#pic").val(); var picArray = []; if (str != ''){ picArray = str.split(','); if (picArray.length > 4){ top.layer.alert("轮播图最多上传五张!", { icon: 5, shadeClose: true }); return false; } } //首先插入一个图片标签,src属性为空,宽高设置为100px,暂时设为不可见 $("#move").after(""); //调用getObjectURL函数,返回上传的图片的地址 var data = new FormData(); data.append('file', obj.files[0]); $.ajax({ type: "POST", async: false, contentType: false, processData: false, data: data, url: "/s/file/upload", success: function (data) { if (data.code === 200) { var pic = $("#pic").val(); $('#pic').val(pic == ''?pic+data.data:pic+','+data.data); $('#show'+i).attr('src',data.data);//将图片的路径设置为返回上传的图片的地址 $("#show"+i).show();//将图片设置为可见 $("#del"+i).show(); parent.notifications('success', '上传成功'); } else { parent.notifications('error', '上传失败'); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { parent.notifications('error', '操作失败,请检查网络!'); }, }); i++; } //删除图片 function del(obj) { var str = obj.substring(3); var picUrl = []; picUrl = $("#pic").val().split(","); for(let i=0;i

你可能感兴趣的:(java)