- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试使用 Jetty 将带有 RestTemplate 的文件上传到 Raspberry Pi。在 Pi 上有一个 servlet 正在运行:
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter outp = resp.getWriter();
StringBuffer buff = new StringBuffer();
File file1 = (File) req.getAttribute("userfile1");
String p = req.getParameter("path");
boolean success = false;
if (file1 == null || !file1.exists()) {
buff.append("File does not exist\n");
} else if (file1.isDirectory()) {
buff.append("File is a directory\n");
} else {
File outputFile = new File(req.getParameter("userfile1"));
if(isValidPath(p)){
p = DRIVE_ROOT + p;
final File finalDest = new File(p
+ outputFile.getName());
success = false;
try {
copyFileUsingFileChannels(file1, finalDest);
finalDest.setWritable(true);
success = true;
} catch (Exception e) {
e.printStackTrace();
}
if (success){
buff.append("File successfully uploaded.\n");
}
else{
buff.append("Failed to save file.");
}
}
else{
buff.append("Invalid path.\n");
}
}
outp.write(buff.toString());
}
我可以用 curl 成功地做到这一点
curl --form userfile1=@/home/pi/src/CreateNewFolderServlet.java --form press=OK localhost:2222/pi/GetFileServlet?path="/media/"
这是应该在 webapp 上具有相同功能的方法。
@ResponseBody
@RequestMapping(value="/upload/",method=RequestMethod.POST ,produces = "text/plain")
public String uploadFile(MultipartHttpServletRequest request2, HttpServletResponse response2){
Iterator<String> itr = request2.getFileNames();
MultipartFile file = request2.getFile(itr.next());
System.out.println(file.getOriginalFilename() +" uploaded!");
System.out.println(file.toString());
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("userfile1",file);
//reqEntity.addPart("userfile1", file);
String path="/public/";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
System.out.println("1");
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<MultiValueMap<String, Object>>(parts, headers);
String url = url2+"/pi/GetFileServlet?path="+path;
System.out.println("2");
/* restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
restTemplate.getMessageConverters().add(
new MappingJackson2HttpMessageConverter());*/
System.out.println("3");
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request,String.class);
System.out.println("4");
System.out.println("response : " +response);
if(response==null||response.getBody().trim()==""){
return "error";
}
return response.getBody();
}
这是我得到的输出:
ui-elements.html 已上传!
org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@47e7673e
1
2
3
如您所见,未打印数字 4控制台也不异常(exception)。调试时发现异常:
org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: org.springframework.web.multipart.support.StandardMultipartFile["inputStream"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: org.springframework.web.multipart.support.StandardMultipartFile["inputStream"])
最佳答案
读取 ByteArrayResource
中的整个文件可能是大文件的内存消耗问题。
您可以使用 InputStreamResource
在 spring mvc Controller 中代理文件上传:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<?> uploadImages(@RequestPart("images") final MultipartFile[] files) throws IOException {
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
String response;
HttpStatus httpStatus = HttpStatus.CREATED;
try {
for (MultipartFile file : files) {
if (!file.isEmpty()) {
map.add("images", new MultipartInputStreamFileResource(file.getInputStream(), file.getOriginalFilename()));
}
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
String url = "http://example.com/upload";
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
response = restTemplate.postForObject(url, requestEntity, String.class);
} catch (HttpStatusCodeException e) {
httpStatus = HttpStatus.valueOf(e.getStatusCode().value());
response = e.getResponseBodyAsString();
} catch (Exception e) {
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
response = e.getMessage();
}
return new ResponseEntity<>(response, httpStatus);
}
class MultipartInputStreamFileResource extends InputStreamResource {
private final String filename;
MultipartInputStreamFileResource(InputStream inputStream, String filename) {
super(inputStream);
this.filename = filename;
}
@Override
public String getFilename() {
return this.filename;
}
@Override
public long contentLength() throws IOException {
return -1; // we do not want to generally read the whole stream into memory ...
}
}
关于java - 如何使用 restTemplate Spring-mvc 发送 Multipart 表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28408271/
根据HTML specs : If the contents of a file are submitted with a form, the file input should be identif
我能够找到很多关于 multipart/form-data 的信息,但关于 multipart/related 的信息却不多。在协议(protocol)/请求格式方面,谁能解释一下这两个http规范在
我尝试从项目详细信息页面添加图像。图像添加成功,但是当我尝试在 itemdetails 页面显示图像时,出现异常 org.springframework.web.multipart.Multipart
在 Spring Boot 中,对于分段上传,我看到许多教程站点都建议具有以下属性之一:spring.http.multipart.enabled=false或者spring.servlet.mult
我正在尝试向服务器发送多部分请求,但出现以下异常 HTTP 状态 500 - 请求处理失败;嵌套异常是 org.springframework.web.multipart.MultipartExcep
情况: 从 Node.js(通过 Node 核心 HTTPS 模块)向 spring-boot Java API 提交多部分表单请求。 API 需要两个表单数据元素: “路线” "file" 完全错误
上传到 webapi Controller 时,我仅在某些文件上收到错误。 错误是“MIME 多部分流。MIME 多部分消息不完整” 似乎该错误与某种未良好终止的 POST 数据相关联,但当我使用 f
我有一个有效的解决方案,但似乎很愚蠢,需要它。 这是我的工作解决方案: @PreAuthorize("isAuthenticated()") @ApiOperation(value = "Takes
这个问题已经有答案了: How can I upload files to a server using JSP/Servlet and Ajax? (4 个回答) 已关闭2 年前。 我尝试用java
我尝试通过包含的 CURL 发布 multipart/form-data, A JSON Object Stream object pdf and jpeg file curl -i -X POS
我在表单帖子中遇到了土耳其语字符问题, 我在尝试以下代码时遇到问题, // some input 但是当我尝试这个时它工作正常 // some input 为什么会这样? 最佳答案 在第一个示
我花了几天时间让 Spring Boot Upload 文件工作,但是,和 Spring 一样,你不知道魔法是如何工作的,即使在使用这个框架多年之后 - 你必须用谷歌搜索大量时间来解开哪里出了问题并解
我正在编写一个脚本,用于将文件上传到需要多部分请求的 cgi 脚本,例如 HTML 页面上的表单。 boundary 是一个唯一的标记,用于注释请求正文中的文件内容。这是一个示例正文: --BOUND
我有一个带有 Netty 的 jersy 2.13 的服务器应用程序,我尝试上传带有“multipart/form-data”的文件,但出现此错误。 错误信息: 7605 10:01:49.309
来自文档:“当您使用 TransferManager 下载文件时,该实用程序会自动确定对象是否为多部分” 来源:https://aws.amazon.com/fr/blogs/developer/pa
我需要有关发送多部分发布请求的帮助。主要问题是服务器无法识别我请求的帖子正文部分。服务器端在 android 上运行良好,但在 Qt 和 NetworkAccessManager 上运行不佳。 代码如
在 fragment B 中,我有一个用于将图像提交到服务器的提交按钮。单击提交按钮时,它将返回到 fragment A。我使用 Multipart 将图像上传到服务器,并且该进程在 Thread 上
我目前正在使用 Spring Boot v1.3.0.BUILD-SNAPSHOT 和 Spring v4.2.2.BUILD-SNAPSHOT。 如果我尝试执行多文件上传(通过 angular):
当我使用 JavaMailSender 发送带有附件的电子邮件时,它总是失败并抛出以下异常: org.springframework.mail.MailSendException: Failed me
我正在尝试在 NodeJS 上手动解析 multipart/formdata 请求。 请求中的所有内容均已正确解析(文件除外)。我正在读取文件数据,但它的长度比原始的短(在fiddler中,选择hex
我是一名优秀的程序员,十分优秀!