美文网首页小程序
微信小程序上传图片springboot接口

微信小程序上传图片springboot接口

作者: 丁忠康 | 来源:发表于2017-12-11 12:41 被阅读681次

    一:在idea项目中创建IndexController,

    //处理文件上传

    @RequestMapping(value ="/uploadimg", method = RequestMethod.POST, consumes ="multipart/form-data")

    @ResponseBody

    publicString uploadImg(HttpServletRequest request)throws Exception

    {

    1.获取文件请求过来的图片

    ApplicationPart image = (ApplicationPart) request.getPart("file");

    2.获得图片的输入流

    InputStream in = image.getInputStream();

    3.获得项目路径

    String webPath = request.getServletContext().getRealPath("/");

    4.获得文件路径

    String path = webPath +"imgupload\\"+ image.getSubmittedFileName();

    5.把文件流转成文件

    inputstreamtofile(in,newFile(path));

    6.文件名切割

    String[] names=image.getSubmittedFileName().split(".");

    //返回json

    returnnames[0];

    }

    //InputStream,String,File相互转化

    private voidinputstreamtofile(InputStream ins, File file)

    {

    OutputStream os =null;

    try

    {

    os =newFileOutputStream(file);

    intbytesRead =0;

    byte[] buffer =new byte[8192];

    while((bytesRead = ins.read(buffer,0,8192)) != -1)

    {

    os.write(buffer,0, bytesRead);

    }

    System.out.println("inputstreamtofile");

    }catch(FileNotFoundException e)

    {

    e.printStackTrace();

    }catch(IOException e)

    {

    e.printStackTrace();

    }finally

    {

    try

    {

    if(os !=null)

    {

    os.close();

    }

    if(ins !=null)

    {

    ins.close();

    }

    }catch(IOException e)

    {

    e.printStackTrace();

    }

    }

    }

    相关文章

      网友评论

        本文标题:微信小程序上传图片springboot接口

        本文链接:https://www.haomeiwen.com/subject/zediixtx.html