zoukankan      html  css  js  c++  java
  • java 图片上传


    代码是最有力量的,嘎嘎

    @CrossOrigin
    @ApiOperation(value = "上传图片", notes = "上传图片", httpMethod = "POST")
    @ApiImplicitParam(name = "file", value = "图片路径", required = true, dataType = "file")
    @ResponseBody
    @PostMapping("/uploadImage")
    public ResultSet uploadImage(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request)
    throws IOException {
    // 上传的图片只允许是 png 或者jpg 中的格式
    if (file.getOriginalFilename().contains(".png") || file.getOriginalFilename().contains(".jpg")) {
    // 根据相对路径转化为真实路径
    String rootpath = request.getSession().getServletContext().getRealPath(File.separator);// 获得web应用的绝对路径
    File createFile = new File(rootpath + "/image/");
    if (!createFile.exists()) {// 判断文件是否存在如果不存在则自动创建文件夹
    createFile.mkdir();
    }
    //String uuid = IdGen.uuid() + "_";// 随机生成一个唯一性的id 确保apk文件重名
    File f = new File(rootpath + "/image/" + file.getOriginalFilename());
    if (f.exists()) {//上传的文件已经存在,则提示用户重新上传 apk 或者重命名
    return ResultSet.getFail("文件已经存在,请重新上传或者重命名");
    } else {
    System.out.println(rootpath);
    file.transferTo(f); // 将上传的文件写入到系统中

    return ResultSet.getSuccess(rootpath +"/image/" + file.getOriginalFilename());
    }
    } else {
    return ResultSet.getFail("上传文件失败");
    }
    }


    另一种

    @RequestMapping(value="/uploadPictures",method=RequestMethod.POST)
    public Object uploadHeadPic(@RequestParam("file")CommonsMultipartFile file,InputStream inputStream,HttpServletRequest request) {
    String uuid = UUID.randomUUID().toString().trim();
    String fileN=file.getOriginalFilename();
    int index=fileN.indexOf(".");
    String fileName=uuid+fileN.substring(index);
    try {
    File fileMkdir=new File("F:\photoTest");

    if(!fileMkdir.exists()) {
    fileMkdir.mkdir();
    }
    //定义输出流 将文件保存在D盘 file.getOriginalFilename()为获得文件的名字
    FileOutputStream os = new FileOutputStream(fileMkdir.getPath()+"\"+fileName);
    InputStream in = file.getInputStream();
    int b = 0;
    while((b=in.read())!=-1){ //读取文件
    os.write(b);
    }
    os.flush(); //关闭流
    in.close();
    os.close();
    } catch (Exception e) {
    return Result.getFail("图片上传失败);
    }
    return Result.getSuccess(fileN);
    }



    用到代码的小伙伴给我点个赞呀
  • 相关阅读:
    线程
    sqlite3数据库操作
    20、android解决方案(转载)
    19、android面试题整理(自己给自己充充电吧)
    18、ESC/POS指令集在android设备上使用实例(通过socket)
    17、android设备如何防止屏幕休眠(转载)
    16、根据年月日获取周几 以及整理的日期常用的工具类
    15、android 用toast实现简单的进度显示
    14、到底改如何区分android的平板、电视、手机
    13、主线程任务太多导致异常退出(The application may be doing too much work on its main thread)
  • 原文地址:https://www.cnblogs.com/shenhaha520/p/10484652.html
Copyright © 2011-2022 走看看