android部分代码:
public Boolean uploadFile(File file, String urlStr) {
Boolean result = false;
String BOUNDARY = "letv"; // 边界标识 随机生成
String PREFIX = "--", LINE_END = "\r\n";
//String CONTENT_TYPE = "application/json"; // json
String CONTENT_TYPE = "multipart/form-data";
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
+ BOUNDARY);
if (file != null) {
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream(
conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"upload\"; filename=\"" + file.getName() + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024 * 1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
if (res == 200) {
result = true;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return result;
}
SpringBoot服务器中接收:
@RequestParam("upload") 对应Android代码中: name=\"upload\";
@RequestMapping("/uploadAudio")
@ResponseBody
public void uploadAudio(@RequestParam("upload") MultipartFile file) {
if (!file.isEmpty()) {
String filename = file.getOriginalFilename();
System.out.println("Load fn:" + filename);
//System.out.println("Load uploadfile:" + fname);
try {
String fileurl = "D:\\/" + filename;
File f = new File(fileurl);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
out.write(file.getBytes());
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}else {
System.out.println("上传失败,因为文件是空的.");
}
}
总结一下,springboot和传统的spring框架文件上送接收方式不一样,如果用传统方式,不是参数传不过去就是传入的文件没有内容等,这问题搞了两天才发现,太坑了......。