使用DiskFileItemFactory和MultipartE

2019-01-29  本文已影响0人  嘎嘣脆哦哦

接口

{
final ResultMessage message =new ResultMessage();

message.setErrno(ErrorNumConsts.OPERATION_ERROR);

message.setErrmsg("upload failed");

try {

      DiskFileItemFactory factory =new DiskFileItemFactory(10240, new File(TEMP_PATH));

      ServletFileUpload upload =new ServletFileUpload(factory);

     upload.setHeaderEncoding("UTF-8");

     List items = upload.parseRequest(request);

    if (items.size() ==0) {

        message.setErrno(ErrorNumConsts.PARAM_ERROR);

        message.setErrmsg("file not be null");

        return message.toString();

      }

    items.forEach(fileItem -> {

    if (!fileItem.isFormField()) {

    InputStream in =null;

     try {

            in = fileItem.getInputStream();

      }catch (IOException e) {

            logger.warn(ExceptionUtils.getExceptionStackTrace(e));

      }

    if (in ==null) {

        return;

      }

    ByteArrayOutputStream baos =new ByteArrayOutputStream();

      try {

            IOUtils.copy(in, baos);

      }catch (IOException e) {

            logger.warn(ExceptionUtils.getExceptionStackTrace(e));

            ResultMessageUtil.setErrorResultMessage(message, ErrorNumConsts.OPERATION_ERROR,

            "流拷贝异常");

            return;

      }

    try {

        Long total = FileUtil.getFileLineNum(new ByteArrayInputStream(baos.toByteArray()));

        if (total >NUM_TOTAL) {

                ResultMessageUtil.setErrorResultMessage(message, ErrorNumConsts.PARAM_ERROR,

              "上传文件行数超过" + (NUM_TOTAL -1) +"行限制");

                return;

        }

    }catch (Exception e) {

        logger.warn(ExceptionUtils.getExceptionStackTrace(e));

        ResultMessageUtil.setErrorResultMessage(message, ErrorNumConsts.OPERATION_ERROR,

            "判断文件记录条数异常");

        return;

      }

    String fileName = fileItem.getName();

      // different browser different file name

      fileName = fileName.substring(fileName.lastIndexOf("\\") +1).trim();

      String taskId =null;

      try {

            taskId = getTaskId();

      }catch (Exception e) {

        logger.warn(ExceptionUtils.getExceptionStackTrace(e));

        return;

      }

    fileName = taskId +"-" + fileName;

    String key = UUIDUtil.getUUID();

    try {

        RedisFacade redisFacade = RedisFacade.getInstance();

        String reidsKey =PRE_FIX + fileName;

        redisFacade.set(reidsKey, key);

        redisFacade.expire(reidsKey, TIME_PERIOD);

      }catch (Exception e) {

        logger.warn(ExceptionUtils.getExceptionStackTrace(e));    

        ResultMessageUtil.setErrorResultMessage(message, ErrorNumConsts.OPERATION_ERROR,

            "redis error");

        return;

      }

try {

        GIFT gift = GIFTUtil.upLoad(UPLOAD_URL, key, fileName,new                  

           ByteArrayInputStream(baos.toByteArray()));

        if (gift !=null) {

            ResultMessageUtil.setErrorResultMessage(message, ErrorNumConsts.SUCCESS,

              "upload file success");

          JSONObject object =new JSONObject();

          object.put("taskId", taskId);

          object.put("fileName", fileName);

          message.setData(object);

        }

}catch (Exception e) {

logger.warn(ExceptionUtils.getExceptionStackTrace(e));

        ResultMessageUtil.setErrorResultMessage(message, ErrorNumConsts.OPERATION_ERROR,

            "upload failed");

      }

try {

         in.close();

      }catch (IOException e) {

         logger.warn("close input stream failed");

      }

        fileItem.delete();

    }

});

}catch (FileUploadException e) {

logger.warn(ExceptionUtils.getExceptionStackTrace(e));

}

return message.toString();

}

GiftUtil.upload

public static GIFTupLoad(String url, String key, String fileName, InputStream stream)throws Exception {

checkParams(url,key,fileName,stream);

    CloseableHttpClient client = HttpClients.createDefault();

    HttpPost post =new HttpPost(getUrl(url,key));

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setCharset(Charset.forName("UTF-8"));//设置请求的编码格式

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    //1,form key 2,file input strem ,3,content-type; 4,file name

    builder.addBinaryBody("filecontent",stream, ContentType.MULTIPART_FORM_DATA,fileName);

    HttpEntity entity = builder.build();

    post.setEntity(entity);

    HttpResponse response =null;

    try {

response =  client.execute(post);

        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

String data = EntityUtils.toString(response.getEntity());

            return JSONObject.parseObject(data,GIFT.class);

        }

throw new Exception("upload failed["+response.getStatusLine().getStatusCode()+"]:" + response.getStatusLine().getReasonPhrase());

    }finally {

if(response !=null){

((CloseableHttpResponse) response).close();

        }

}

}

具体步骤如下:

1、创建DiskFileItemFactory对象,设置缓冲区大小和临时文件目录

2、使用DiskFileItemFactory 对象创建ServletFileUpload对象,并设置上传文

      件的大小限制。

3、调用ServletFileUpload.parseRequest方法解析request对象,得到一个保

      存了所有上传内容的List对象。

4、对list进行迭代,每迭代一个FileItem对象,调用其isFormField方法判断

       是否是上传文件

5、 为普通表单字段,则调用getFieldName、getString方法得到字段名和字段

      值

6、 为上传文件,则调用getInputStream方法得到数据输入流,从而读取上传

      数据。

注: 我们这里调用giftUtil.upLoad实现http上传,即使用MultipartEntityBuilder。

一个小细节即:

ByteArrayOutputStream baos = newByteArrayOutputStream();

IOUtils.copy(in, baos);

将字符输入流转成byte数组流,因为输入流只能用一次,这里转成byte数组流可以复用,但这个接口并未复用。

上一篇下一篇

猜你喜欢

热点阅读