上传MultipartFile文件到外部服务器

在springmvc中,上传文件是一个经常用到的功能。第一种情况,如果是上传到本地服务器电脑上的话,很好解决,在pom.xml文件中添加uploadFile依赖,核心代码大致如下

<!-- pom文件添加上传的包 ,用于文件上传-->
 <dependency>
     <groupId>commons-fileupload</groupId>
     <artifactId>commons-fileupload</artifactId>
     <version>1.3.1</version>
 </dependency>


 <!-- servlet配置文件对文件上传的处理,这里声明的id必须为multipartResolver-->
 <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
    <!--  最大为10M,单位为字节   -->
    <property name="maxUploadSize" value="10485760"></property>
    <property name="defaultEncoding" value="utf-8"></property>
    <property name="maxInMemorySize" value="40960"></property>
 </bean>
<form action="/upfile.do" method="post" enctype="multipart/form-data">
    <c:if test="${picture!=null}">
        <img src="/upfile/${picture}" width="100px" height="100px">
    </c:if>
    <input type="file" name="picture">
    <input type="submit">
</form>
@Controller
public class uploadFile {

    @RequestMapping("/upfile.do")
    public String upfile(Model model, HttpServletRequest request, MultipartFile picture)
            throws IOException {
        request.setAttribute("picture",picture.getOriginalFilename());
        String picName= UUID.randomUUID().toString();
        String oriName=picture.getOriginalFilename();
        String extName=oriName.substring(oriName.lastIndexOf("."));

        picture.transferTo(new File("D:/upfile1/"+picName+extName));
        System.out.println(request.getParameter("picture"));
        return "Views/uploadPicture";
    }
}

第二种情况就是,通常我们文件服务器是单独分开的,它提供一个接口,以供我们调用。那么这时有两种方式,第一种,还是采用类似上面控制器内方法的代码逻辑,接口提供MultipartFile 文件类型(当然,你可能还要带其它参数),第二种就是通过字节数组或者文件流的形式,接口提供文件流或字节数组的。这里第二种就不做介绍,比较好处理,就跟传递其它基本类型一样,主要介绍第一种,配置上基本一致,主要的不同在于代码的处理,如下。


    <!-- 头像文件上传表单 -->
    <form id="uploadForm" action="/user/uploadPhoto" method="post" enctype="multipart/form-data">
        <input id="avatarFileInput" name="avatar" accept="image/*" type="file" hidden="hidden">
        <input type="submit" hidden="hidden">
    </form>

$.ajax({
    url: "/upload/file",
    type: 'POST',
    cache: false,
    data: new FormData($("#uploadForm")[0]),
    processData: false,
    contentType: false,
    success: function (result) {
    },
    error: function (err) {
    }
});
  @RequestMapping(value = "/upload/file", method = RequestMethod.POST)
  public JSONObject UpdateUserFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
    Map<String,Object> map = new HashMap<String,Object>();
    Map<String, Object> data = new HashMap<String, Object>();
    if (file== null || file.getSize() <= 0 || file.getSize() >= FILE_MAX_SIZE) {
      map.put("code", -1);
      map.put("info","上传的图片文件不合法");
    } else {
      CloseableHttpClient httpClient = HttpClients.createDefault();
      HttpPost httpPost = new HttpPost(NetConfig.API_url+"api/user/upload/file");
      MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
      String originFileName = file.getOriginalFilename();
      builder.addBinaryBody("file", file.getBytes(), ContentType.MULTIPART_FORM_DATA, originFileName);// 设置上传文件流(需要是输出流),设置contentType的类型
      builder.addTextBody("opendid",opendid);//post请求中的其他参数
      HttpEntity entity = builder.build();
      httpPost.setEntity(entity);
      httpPost.setEntity(entity);
      HttpResponse response = httpClient.execute(httpPost);// 执行提交
      HttpEntity responseEntity = response.getEntity();//接收调用外部接口返回的内容
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String jsonresult = EntityUtils.toString(responseEntity);
        Map newMap = JSON.parseObject(jsonresult);//返回json数据结果集
        if (newMap.get("code").toString().equals("200")) {
          //...
        }
      }
    }
    return (JSONObject)JSONObject.toJSON(map);
  }

相信你也发现了,最重要的核心,就在控制器下UpdateUserFile方法里面的处理,这样才能调用外部API的文件上传接口,并传递MultipartFile 文件类型对象给外部API。这里没有采用okhttp等网络请求框架,而是采用的原始的方式。这样,从页面到ajax,再到controller里面的方法,最后到外部接口再返回调用结果的流程就完成了。

发布了120 篇原创文章 · 获赞 50 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/u014650759/article/details/103862260