Coder Social home page Coder Social logo

spring-boot-qiniu-example's Introduction

spring-boot-qiniu-example

spring boot 七牛云上传图片

配置 qiniu.properties

qiniu.access-key = 
qiniu.secret-key = 
qiniu.bucket = 
qiniu.bucket-url = 

Controller

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public String uploadImg(HttpServletRequest request) throws Exception {
        String filePath = "";
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();

            while (iter.hasNext()) {
                // 取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                String fileName = file.getOriginalFilename();
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                DefaultPutRet putRet = upload(file.getBytes(), newFileName);
                filePath += qiNiuProperties.getBucketUrl() + putRet.key + ",";
            }
            if (filePath.endsWith(",")) {
                filePath = filePath.substring(0, filePath.length() - 1);
            }
        }
        return filePath;
    }

Test 测试上传

    private MockMvc mvc;

    @Autowired
    private WebApplicationContext wac;


    @Before
    public void setup() {
        this.mvc = MockMvcBuilders.webAppContextSetup(this.wac).alwaysExpect(status().isOk()).addFilters(new CharacterEncodingFilter()).build();
    }


    @Test
    public void testUpload() throws Exception {
        String uri = "/qiniu/upload";
        File f = new File("/Users/sungang/Pictures/timg2.jpeg");
        FileInputStream fis = new FileInputStream(f);
        MockMultipartFile upload = new MockMultipartFile("upload", f.getName(), "multipart/form-data", fis);
        MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.fileUpload(uri).file(upload).accept(MediaType.APPLICATION_JSON)).andReturn();
        int status = mvcResult.getResponse().getStatus();
        String content = mvcResult.getResponse().getContentAsString();

        Assert.assertEquals(status, 200);
        Assert.assertNotNull(content);

        System.out.println(status);
        System.out.println(content);
    }

输出结果:

spring-boot-qiniu-example's People

Contributors

aillamsun avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.