uniquejava / blog

My notes regarding the vibrating frontend :boom and the plain old java :rofl.
Creative Commons Zero v1.0 Universal
11 stars 5 forks source link

spring mvc request #195

Open uniquejava opened 6 years ago

uniquejava commented 6 years ago

注意: 在client端有选择的使用post和postJSON方法.. postJSON只能用RequestBody一次性接收 .

各种方式

@PathVariable处理uri中的参数 @GetMapping("/users/{username}")

https://course.tianmaying.com/spring-mvc+path-variable#

@RequestHeader@CookieValue处理请求头和其中的Cookie部分

@RequestParam即可以处理queryString也可以处理body中的参数, 只能处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST

@RequestyBody 处理Content-Type: application/json, application/xml,可能直接映射成对象. @RequestyBody 也可以处理application/x-www-form-urlencoded编码的内容,例如, 但是整个body是一个string类型的字段 -- &拼接的字符串)

// body是一个json array
public void oh(HttpServletRequest request, @RequestBody List<MyBean> beans)

// 参数中有array
public String my(HttpServletRequest request,
    @RequestParam(name = "fileName[]", required = false) String[] fileName,
    @RequestParam(name = "page", defaultValue = "1") int page,
    @RequestParam(name = "limit", defaultValue = "10") int limit) throws Exception {

// 将body接收成一个字符串
@PostMapping(value = "")
public String god(HttpServletRequest request) throws Exception {
    String jsonBody = IOUtils.toString(request.getInputStream(), "UTF-8");

// 将body接收成一个字符串 (以&分开的key, value pair)
public String createCollection(HttpServletRequest request, @RequestBody String params)

// 接收文件
@PostMapping("/upload")
public Map<String, Object> singleFileUpload(@RequestParam("file") MultipartFile file, String encoding, boolean hasHeader)

// 接收多文件
@RequestMapping(value = "/import", method = RequestMethod.POST)
public void importLicense(@RequestParam("files") MultipartFile[] files) throws Exception {
    for (MultipartFile uploadedFile : files) {
        String fileName = uploadedFile.getOriginalFilename();
        File destFile = new File(xxxx, fileName);
        logger.info(destFile.getAbsolutePath());
        // java.io.FileNotFoundException: 
        // /opt/xxx/wlp/usr/servers/defaultServer/workarea/org.eclipse.osgi/64/data/temp/default_node/SMF_WebContainer/ctx/path/to/xxx.dat (No such file or directory)
        // uploadedFile.transferTo(destFile);
        FileCopyUtils.copy(uploadedFile.getInputStream(),  new FileOutputStream(destFile));
    }

}

注意MultipartFile.transferTo有严重的bug, 不要用这个方法.

另见: https://stackoverflow.com/a/19469782/2497876 另见: https://segmentfault.com/a/1190000014766457

uniquejava commented 6 years ago

Response

sendFile

Get请求

http://dolszewski.com/spring/how-to-bind-requestparam-to-object/

多文件上传同时带其他非文件类型的字段

https://stackoverflow.com/questions/27294838/how-to-process-a-multipart-request-consisting-of-a-file-and-a-json-object-in-spr

最终从这里得到了答案 https://stackoverflow.com/questions/29370143/spring-mvc-upload-file-with-other-fields 前端 XxxEdit.Vue

const data = await form.validate()
try {
  let formData = new FormData()
  for (let prop in data) {
    formData.append(prop, data[prop])
  }
  fileList.value.forEach((file) => formData.append('files', file))
  createKnowledge(formData);
...
}

export function createKnowledge(knowledge: FormData) {
  return http.post<void>('/api/knowledges', knowledge, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

XxxController.java

@PostMapping
public void create(@Valid KnowledgeInput record) {
    knowledgeService.create(record);
}

XxxInput.java

@Data
@ToString
public class KnowledgeInput {
    /* other fields */
    private String keyword;

    /**
     * attachments
     */
    private MultipartFile[] files;
}