OSS存储图片

1,html的form表单

<form action="/oss" id="oss">
        <input type="hidden" name="UPhoto1" id="headImg">
        <input type="file" name="mfile1" id="upload"
               accept="image/*" class="input-file"  			multiple="multiple">
    </form>

2,JavaScript
当图片选择器改变时触发post请求,提交图片返回url

 $("#upload").change(function() {
            upload_files2();
        });

        function upload_files2() {
            var formData =new FormData();
            formData.append('file', $('#upload')[0].files[0]);
            $.ajax({
                url: "/oss/uploadFiles",
                type:'POST',
                data: formData,
                async:false,
                cache:false,
                contentType:false,
                processData:false,
                success:function (data) {
                    if (data.success){
                        //$("#headImg").val(data.msg);
                        alert("成功了!" + data.msg);
                    }else {
                        alert("失败了!" + data.msg);
                    }
                },
                error:function (data) {
                    alert("失败了!" + data.msg);
                }

            });

        }

3,controller接受请求和图片

@Controller
@CrossOrigin
@RequestMapping("/oss")
public class OSSController extends BaseController {
    @Autowired
    private OssServiceImpl ossServiceImpl;
    @PostMapping("/uploadFiles")
    @ResponseBody
    public AjaxResult uploadFiles(@RequestParam(value ="file") MultipartFile file){
        String url = ossServiceImpl.uploadImg(file);
        return AjaxResult.me(true,url);
    }
}

4service层,上传图片到阿里云oss,其中参数都放在OSSConfig配置类中

	 private OSS getConnect() {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OSSConfig.ENDPOINT, OSSConfig.ACCESSKEYID,
                OSSConfig.ACCESSKEYSECRET);
        return ossClient;
    }
    private void closeConnect(OSS ossClient) {
        ossClient.shutdown();
    }
    @Override
    public String uploadImg(MultipartFile file) {
        OSS connect = null;
        try {
            InputStream inputStream = file.getInputStream();
            connect = getConnect();

            //生成文件名
            String filePath = DateUtil.getTodayStr2();
            String fileName = UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename();


            PutObjectResult result = connect.putObject(OSSConfig.BUCKETNAME,
                    filePath+"/"+fileName,    // 上传的路径和名称
                    inputStream);
            String url = "https://"+OSSConfig.BUCKETNAME
                    +"."+OSSConfig.ENDPOINT+"/"+filePath+"/"+file.getOriginalFilename();
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            closeConnect(connect);
        }
        return null;
    }

你可能感兴趣的:(aliyun)