java Web项目上传图片储存到项目下

本文介绍了一个Java Web应用程序中的图片上传功能实现,包括限制文件大小、自定义存储路径及异常处理。同时,详细展示了如何读取本地文件内容,涵盖了流操作、字符编码转换及异常捕获。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 @RequestMapping(value = "/mi/upload", method = RequestMethod.POST)
    @ResponseBody
    public MyResponse upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        long size = file.getSize();
        if(size>1024*1024*2){
            throw new MyException("图片大小不能超过2M");
        }
        String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
        //String webappRoot = classpath.replaceAll("WEB-INF/classes/", "");
        //可以自定义路径
        File dir = new File(classpath+"/images");
        if(!dir.isDirectory()){
            dir.mkdirs();
        }
        String accessUrl =  "/images/"+System.currentTimeMillis()+file.getName()+".jpg";
        try {
            File file1 = new File(classpath+accessUrl);
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException("上传失败");
        }
  }

2.读取本地文件内容

//        String filepath = "E:/upload/test.txt";//E盘下的文件夹的目录
//        File targetFile = new File(filepath);//File类型可以是文件也可以是文件夹
//
//        // File targetFile = new File(path);
//        if (!targetFile.exists()) {
//            targetFile.mkdirs();
//        }
//        //保存到本地的文件
//        // File saveFile = new File(path + fileName);
//        FileInputStream fileInput = null;
//        String rs = "";
//        try {
//            // 通过File对象构建一个流对象
//            fileInput = new FileInputStream(targetFile);
//            // 读取数据,并将读取的数据存储在数组中
//            byte[] data = new byte[(int) targetFile.length()];
//            // 读取流中的第一个字节数据
//            int n = fileInput.read();
//            // 读取的游标位置
//            int i = 0;
//            // 判断是否读到最后一个字符
//            while (n != -1) {
//                data[i] = (byte) n;
//                i++;
//                n = fileInput.read();
//            }
//            rs = new String(data, "GBK");
//            System.out.println(rs);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        try {
//            file.transferTo(targetFile);
//            return new MyResponse(rs);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new MyResponse(ResponseCode.OPERATE_FAIL, e.getMessage());
//        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值