java的文件上传

1.首先我会判断上传的文件格式是不是我要的

    public ServiceResult<List<String>> mutiFileUploadHandle(MultipartFile[] uploadFile) {
        ServiceResult<List<String>> result = new ServiceResult<>();
        // 判断文件名是否符合格式
        for (MultipartFile file : uploadFile) {
            if (file.getSize() > 0) {
                String fileName = file.getOriginalFilename();
                if (StrUtil.isBlank(fileName)) {
                    result.setSuccess(false);
                    result.setMessage("文件不存在,请上传正确的文件");
                    return result;
                }
                // 符合以下几种才进行鉴定
                if (fileName.toLowerCase().endsWith("jpg") || fileName.toLowerCase().endsWith("png")
                    || fileName.toLowerCase().endsWith("bmp")) {

                } else {
                    result.setSuccess(false);
                    result.setMessage("对不起,目前仅支持jpg、png、bmp格式的图片");
                    return result;
                }
            }
        }
        // 鉴定
        List<String> list = new ArrayList<>();
        for (MultipartFile file : uploadFile) {
            try {
                byte[] bytes = file.getBytes();
                String encode = Base64.getEncoder().encodeToString(bytes);
                list.add(encode);
            } catch (IOException e) {
                _logger.error(e.toString());
            }
        }

        result.setSuccess(true);
        result.setResult(list);
        return result;
    }

//其次上传图片并返回他的保存路径

   /**
     * 20190929
     * 头像上传
     * @param file 上图的图片
     * @param flag:
     *          <li>true:平台上传;</li>
     *          <li>false:商家上传;</li>
     * @return
     */
    public String headPicUpload(File file,Integer userId, boolean flag) {
        String fileKey = "pic";
        Map<String, String> params = new HashMap<String, String>();
        if (flag) {
        //作为条件,如果是平台端的图片
            params.put(ConstantsEJS.BRAND, ConstantsEJS.BRAND);
        } else {
            params.put(ConstantsEJS.SELLER_ID, userId + "");
        }

//主要方法
        uploadFile(file, fileKey, BRAND_IMAGE_PATH, params);
        return result;
    }

下面是uploadFile方法

 /**
     * 上传文件
     * @param file 需要上传的文件
     * @param fileKey 在网页上< input type=file name=xxx/> xxx就是这里的fileKey
     * @param RequestURL 请求的URL
     * @param param 传递参数
     */
    public void uploadFile(File file, String fileKey, String RequestURL,
                           Map<String, String> param) {
        if (file == null || (!file.exists())) {
            return;
        }

        requestTime = 0;

        long requestTime = System.currentTimeMillis();
        long responseTime = 0;

        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(readTimeOut);
            conn.setConnectTimeout(connectTimeout);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", CHARSET); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            //			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            /**
             * 当文件不为空,把文件包装并且上传
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = null;
            String params = "";

            /***
             * 以下是用于上传参数
             */
            if (param != null && param.size() > 0) {
                Iterator<String> it = param.keySet().iterator();
                while (it.hasNext()) {
                    sb = null;
                    sb = new StringBuffer();
                    String key = it.next();
                    String value = param.get(key);
                    sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
                    sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"")
                        .append(LINE_END).append(LINE_END);
                    sb.append(value).append(LINE_END);
                    params = sb.toString();
                    dos.write(params.getBytes());
                    //					dos.flush();
                }
            }

            sb = null;
            params = null;
            sb = new StringBuffer();

            Date date = new Date();
            String fileName = DateUtil.format(date,"yyyyMMddHHmmss") + UUID.randomUUID().toString().replace("-", "") + ".png";

            sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
            sb.append("Content-Disposition:form-data; name=\"" + fileKey + "\"; filename=\""
                      + fileName + "\"" + LINE_END);
            sb.append("Content-Type:image/pjpeg" + LINE_END); // 这里配置的Content-type很重要的 ,用于服务器端辨别文件的类型的
            sb.append(LINE_END);
            params = sb.toString();
            sb = null;

            dos.write(params.getBytes());
            /**上传文件*/
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            is.close();

            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();

            /**
             * 获取响应码 200=成功 当响应成功,获取响应的流
             */
            int res = conn.getResponseCode();
            responseTime = System.currentTimeMillis();
            requestTime = (int) ((responseTime - requestTime) / 1000);

            //删除临时文件
            file.delete();

            if (res == 200) {
                InputStream input = conn.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }
                result = sb1.toString();
                return;
            } else {
                return;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return;
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值