春季:文件上传RESTFUL网络服务
2022-09-02 09:23:30
我正在使用Spring 4.0为RESTFUL Web服务创建POC。如果我们只传递 String 或任何其他基本 dataype,则工作正常。
@RequestMapping(value="/upload/file", method=RequestMapping.post)
public String uploadFile(@RequestParam("fileName", required=false) String fileName){
logger.info("initialization of object");
//----------------------------------------
System.out.Println("name of File : " + fileName);
//----------------------------------------
}
这工作正常。但是如果我想将字节流或文件对象传递给函数,我该如何编写具有这些参数的函数?以及如何编写提供传递字节流的客户端?
@RequestMapping(value="/upload/file", method=RequestMapping.post)
public String uploadFile(@RequestParam("file", required=false) byte [] fileName){
//---------------------
//
}
我尝试了这个代码,但得到415错误。
@RequestMapping(value = "/upload/file", method = RequestMethod.POST, consumes="multipart/form-data")
public @ResponseBody String uploadFileContentFromBytes(@RequestBody MultipartFormDataInput input, Model model) {
logger.info("Get Content. ");
//------------
}
Client Code - Using apache HttpClient
private static void executeClient() {
HttpClient client = new DefaultHttpClient();
HttpPost postReqeust = new HttpPost(SERVER_URI + "/file");
try{
// Set Various Attributes
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("fileType" , new StringBody("DOCX"));
FileBody fileBody = new FileBody(new File("D:\\demo.docx"), "application/octect-stream");
// prepare payload
multipartEntity.addPart("attachment", fileBody);
//Set to request body
postReqeust.setEntity(multipartEntity);
HttpResponse response = client.execute(postReqeust) ;
//Verify response if any
if (response != null)
{
System.out.println(response.getStatusLine().getStatusCode());
}
}
catch(Exception ex){
ex.printStackTrace();
}