gpt4 book ai didi

java - 多部分/表单数据 Restful 请求

转载 作者:行者123 更新时间:2023-11-30 06:45:37 26 4
gpt4 key购买 nike

我正在处理按边界划分的 multipart/form-data POST 请求。

POST .... HTTP/1.1
.
.
.
---boundary123
Content-type:application/octet-stream
content-Disposition: form-data filenale="payload.txt" name="someuniquename"
[paylaod content](this is in xml format)
---boundary123
content-type:application/json
content-Disposition:form-data name="someuniquname"
{ID:"999"}
---boundary123

我该如何处理这个多部分请求?我还想在使用 Spring4 和 REST 发出 POST 请求之前验证数据。

最佳答案

您应该遵循以下代码:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileUploadController {
@RequestMapping(value="/singleUpload")
public String singleUpload(){
return "singleUpload";
}
@RequestMapping(value="/singleSave", method=RequestMethod.POST )
public @ResponseBody String singleSave(@RequestParam("file") MultipartFile file, @RequestParam("desc") String desc ){
System.out.println("File Description:"+desc);
String fileName = null;
if (!file.isEmpty()) {
try {
fileName = file.getOriginalFilename();
byte[] bytes = file.getBytes();
BufferedOutputStream buffStream =
new BufferedOutputStream(new FileOutputStream(new File("F:/cp/" + fileName)));
buffStream.write(bytes);
buffStream.close();
return "You have successfully uploaded " + fileName;
} catch (Exception e) {
return "You failed to upload " + fileName + ": " + e.getMessage();
}
} else {
return "Unable to upload. File is empty.";
}
}
@RequestMapping(value="/multipleUpload")
public String multiUpload(){
return "multipleUpload";
}
@RequestMapping(value="/multipleSave", method=RequestMethod.POST )
public @ResponseBody String multipleSave(@RequestParam("file") MultipartFile[] files){
String fileName = null;
String msg = "";
if (files != null && files.length >0) {
for(int i =0 ;i< files.length; i++){
try {
fileName = files[i].getOriginalFilename();
byte[] bytes = files[i].getBytes();
BufferedOutputStream buffStream =
new BufferedOutputStream(new FileOutputStream(new File("F:/cp/" + fileName)));
buffStream.write(bytes);
buffStream.close();
msg += "You have successfully uploaded " + fileName +"<br/>";
} catch (Exception e) {
return "You failed to upload " + fileName + ": " + e.getMessage() +"<br/>";
}
}
return msg;
} else {
return "Unable to upload. File is empty.";
}
}
}

关于java - 多部分/表单数据 Restful 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43729185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com