java 图片上传完整

1.controller

@RestController
@RequestMapping("/example/demojpa/user")
@Api(value="ImgController",tags={"图片"})
public class ImgController {

    @Autowired
    private ImgService imgService;

    //上传图片
    @PostMapping
    @ApiOperation("上传图片")
    public ResponseData uploadImg(@ApiParam(name="file",value="医生照片",required=true)
                                  MultipartFile file){
        imgService.uploadImg(file);
        return ResponseData.success();
    }


}

2.service

@Service
@Transactional(rollbackFor = Exception.class)
public class ImgService {

    /**
     * 上传文件
     * @param multipartFile
     */
    public void uploadImg(MultipartFile multipartFile){
        try {
            String img = saveImg(multipartFile);
            System.out.println(img);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public String saveImg(MultipartFile multipartFile) throws Exception {

        if(multipartFile.equals("") || multipartFile.getSize() <= 0){
            throw new ObjectNotExistException("上传文件图片不能为空!");
        }

        File file = multipartFileToFile(multipartFile);
        //文件名
        String fileName = multipartFile.getOriginalFilename();
        //后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if(!".jpg".equals(suffix) && !".png".equals(suffix) && !".jpeg".equals(suffix)){
            throw new ObjectNotExistException("图片类型错误!");
        }
        //获取文件名称
        String tName = fileName + System.currentTimeMillis();
        //图片写入服务器
        String imgName = FileUtil.copyFile(file,tName);
        return imgName;
    }

    public File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile;
        if(file.equals("") || file.getSize() <= 0){
            return null;
        }else {
            InputStream ins;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = ins.read(buffer, 0, 1024)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3.Utils

public class FileUtil {
    public final static String TARGETPATH = "E:\\work1\\image";
   // public final static String TARGETPATH = "/Users/wgchao/data";
    /**
     * 文件写入
     * @param srcFile 源文件
     * @param targetName 文件名称
     * @return 返回保存后的文件名
     * @throws Exception
     */
    public static String copyFile(File srcFile, String targetName) {
        File target = new File(TARGETPATH);
        //判断目标路径是否是目录
        if (!target.isDirectory()) {
            //throw new Exception("文件路径不存在!");
            //target.getParentFile().mkdirs();
        }

        // 判断是否存在相同的文件名的文件
        File[] listFiles = target.listFiles();
        for (File file : listFiles) {
            if(targetName.equals(file.getName())){
                return targetName + "_01";
            }
        }

        String fileName = srcFile.getName();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        String newFileName = TARGETPATH + File.separator + targetName + suffixName;
        File targetFile = new File(newFileName);
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(targetFile);
            byte[] buf = new byte[8 * 1024];
            int len = 0;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try{
                if(in != null){
                    in.close();
                }
            }catch(Exception e){
                System.out.println("关闭输入流错误!");
            }
            try{
                if(out != null){
                    out.close();
                }
            }catch(Exception e){
                System.out.println("关闭输出流错误!");
            }
        }
        return targetName + suffixName;

    }

    /**
     * 删除文件
     * @param fileName 文件名包含后缀
     * @return
     * @throws Exception
     */
    public static boolean deleteFile(String fileName) throws Exception {
        String allFileName = TARGETPATH + File.separator + fileName;
        File file = new File(allFileName);
        if(file.exists()){
            if(file.isFile()){
                return file.delete();
            }
        }
        return false;
    }

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值