Spring-boot从Android应用程序调用时,不存在所需的请求部分'文件'

时间:2018-06-02 15:25:47

标签: java android spring spring-boot

我有这个Spring启动服务器:https://github.com/hendisantika/spring-boot-file-upload-example我正在尝试编写一个Android应用程序,用于将图片上传到服务器。用于发出POST请求的Android代码是:

String filename = str.substring(str.lastIndexOf("/") + 1);
URL url = new URL("http://" + ip + ":8080/upload");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setDoOutput(true);
c.setRequestMethod("POST");
c.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryxcCLrAVAeeFcNa3t");
c.setRequestProperty("Content-Disposition", "form-data; name=\"file\"; filename=\"" + filename + "\"");
c.connect();
OutputStream output = c.getOutputStream();
myb.compress(Bitmap.CompressFormat.JPEG, 50, output);
fubar(c);
output.close();
int status = c.getResponseCode();
System.out.println(status);

StringBuffer se = new StringBuffer();
InputStream in = null;
if(status >= 400)
  in = c.getErrorStream();
else
  in = c.getInputStream();

Scanner result = new Scanner(in);
String response = result.nextLine();                  
System.out.println(response);                   

运行上述代码时服务器返回的JSON是:

{
  "timestamp":1527951652083,
  "status":400,
  "error":"Bad Request",
  "exception":"org.springframework.web.multipart.support.MissingServletRequestPartException",
  "message":"Required request part 'file' is not present",
  "path":"/upload"
 }

从网页上传文件非常有效。

0 个答案:

没有答案