可以使用JSON和Multipart Form的REST服务 [英] REST Service that can consume both JSON and Multipart Form

查看:119
本文介绍了可以使用JSON和Multipart Form的REST服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Spring MVC中创建一个可以处理JSON和Multipart Form请求的方法。

I need to create a method in Spring MVC that can handle both JSON and Multipart Form requests.

这是我方法的签名:

@RequestMapping(value = { "/upload_image" }, method = RequestMethod.POST)
public @ResponseBody void uploadImage(final ImageDTO image) 

ImageDTO类如下所示:

ImageDTO class looks as following:

public class ImageDTO {
  private String imageUrl;
  private Long imageId;
  private MultipartFile image;

  public String getImageUrl() {
    return imageUrl;
  }

  public void setImageUrl(final String url) {
    this.imageUrl = url;
  }

  public Long getImageId() {
    return imageId;
  }

  public void setImageId(final Long imageId) {
    this.imageId = imageId;
  }

  public MultipartFile getImage() {
    return image;
  }

  public void setImage(MultipartFile image) {
    this.image = image;
  }
}

所以场景是我需要支持两种情况:
1.从表单加载图像,其中Content-Type是多部分形式(所有DTO成员都不为空)
2.使用JSON进行图像上传,仅使用imageUrl。
在这种情况下,请求正文如下所示:

So the scenario is that I need to support two scenarios: 1. Image up load from form, where the Content-Type is multipart-form (all DTO members are not null) 2. Image upload using JSON, using ONLY the imageUrl. In this case, the request body looks like this:

{
    "imageId":"1236",
    "imageUrl":"http://some.image.url",
    "image":null
}

当前实现很好地处理了多部分请求,但是当发送JSON时,ImageDTO对象在其所有成员中都包含NULL。

The current implementation handles the multipart request well, but when sending the JSON, the ImageDTO object contains NULLs in all its members.

是否可以使相同的方法处理两种内容类型?

Is is it possible to make the same method handle both content types?

谢谢。

推荐答案

面对类似的情况,这就是我想出的。两者都不是那么干净的方式,但工作得很好。您需要从客户端发送多部分请求

Had faced a similar situation, and here's what I'd come up with. Both are not-so-clean ways, but work perfectly. You need to send a multipart request from client:

注意:保存文件的变量的数据类型为的InputStream 。您需要相应地更改

Note: The datatype of the variable to hold the file is InputStream. You need to change it accordingly


  1. 这在您不知道文件数量的情况下非常有用
    正在接收您的请求。

  1. This is useful in cases you are not aware of the number of files you are receiving in you request.

// imports
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

// code flow
// HttpServletRequest request
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
private Map<String, InputStream> fileMap = new HashMap<String, InputStream>();

if (ServletFileUpload.isMultipartContent(request)) {

    // get the request content and iterate through
    items = fileUpload.parseRequest(request);

    if (items != null) {
        final Iterator iter = items.iterator();
        while (iter.hasNext()) {
            final FileItem item = (FileItem) iter.next();
            final String fieldName = item.getFieldName();
            final String fieldValue = item.getString();
            // this is for non-file fields
            if (item.isFormField()) {
                switch (fieldName) {
                    case "imageId" :
                    // set inside your DTO field
                    break;

                    // do it for other fields
                }

            } else {
               // set the image in DTO field
            }
        }
    }
}


  • 在这种情况下,你将不得不处理固定数量的
    字段。我在ReST方法中实现如下:

  • In this case, you will have to deal with fixed number of form fields. I had implemented in ReST method as follows:

    @Path("/upload")
    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public ResponseDTO upload(FormDataMultiPart multiPartData) {
    
             // non-file fields
             final String imageId = multiPartData.getField("imageId").getValue();
    
             // for file field    
             final FormDataBodyPart imagePart = multiPartData.getField("image");
             final ContentDisposition imageDetails= imagePart.getContentDisposition();
             final InputStream imageDoc = imagePart.getValueAs(InputStream.class);
    
             // set the retrieved content in DTO
    }
    


  • 这篇关于可以使用JSON和Multipart Form的REST服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆