第一步 首先是要文件传输,类似于文件传输的代码网上一大把
/**
* 上传文件到静态资源服务器
* @param fileType 文件类型(1:图片;2:文件;3:语音)
* @param is 图片文件流
* @param filename 文件名
* @param fileDir 文件目录(模块名/功能名;如:"usercenter/user")
* @param isResize 是否压缩图片
* @param subFileName 子文件名
* @return
*/
@SuppressWarnings("unchecked")
public static String uploadFileToServer(String fileType, InputStream is, String filename, String fileDir,
boolean isResize, String subFileName) {
String res = "";
HttpURLConnection conn = null;
// boundary就是request头和上传文件内容的分隔符
String BOUNDARY = "--------------------------------";
try {
String urlType = "";
if ("1".equals(fileType)) {
urlType = UPLOAD_IMAGE;
} else if ("2".equals(fileType)) {
urlType = UPLOAD_FILE;
} else if ("3".equals(fileType)) {
urlType = UPLOAD_VOICE;
}
URL url = new URL(getServerUploadUrl() + urlType);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 传参数
StringBuffer sb = new StringBuffer();
sb.append("--").append(BOUNDARY).append("\r\n");
sb.append("Content-Disposition: form-data; name=\"fileDir\"").append("\r\n").append("\r\n");
sb.append(fileDir).append("\r\n");
out.write(sb.toString().getBytes());
sb = new StringBuffer();
sb.append("--").append(BOUNDARY).append("\r\n");
sb.append("Content-Disposition: form-data; name=\"isResize\"").append("\r\n").append("\r\n");
sb.append(isResize).append("\r\n");
out.write(sb.toString().getBytes());
if (StrUtil.isNotEmpty(subFileName)) {
sb = new StringBuffer();
sb.append("--").append(BOUNDARY).append("\r\n");
sb.append("Content-Disposition: form-data; name=\"subFileName\"").append("\r\n").append("\r\n");
sb.append(subFileName);
out.write(sb.toString().getBytes());
}
// 没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
String contentType = null;
// contentType非空采用filename匹配默认的图片类型
if (filename.endsWith(".png")) {
contentType = "image/png";
} else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
contentType = "image/jpeg";
} else if (filename.endsWith(".gif")) {
contentType = "image/gif";
} else if (filename.endsWith(".ico")) {
contentType = "image/image/x-icon";
}
if (contentType == null || "".equals(contentType)) {
contentType = "application/octet-stream";
}
sb = new StringBuffer();
sb.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
sb.append("Content-Disposition: form-data; name=\"" + "file" + "\"; filename=\"" + filename + "\"\r\n");
sb.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(sb.toString().getBytes());
DataInputStream in = new DataInputStream(is);
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(res, Map.class);
if (MapUtil.getInt(map, "result") == 1) {
return map.get("content").toString();
} else {
StaticLog.error("上传文件失败:{}", map.get("errmsg"));
return null;
}
} catch (Exception e) {
StaticLog.error(e, "上传文件失败");
return null;
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
}
然后 MultipartFile ,MultipartFile是file的抽象,简而言之就是前端上传后端用MultipartFile接受的抽象类
public void uploadMultipartFile ( MultipartFile attachFile) throws IOException {
String path = uploadFileToServer(attachFile.getInputStream(), attachFile.getOriginalFilename(),
"xxxx/xxxxx/" , "");
consultAttach.setAttachName(attachFile.getOriginalFilename());
consultAttach.setAttachSize(attachFile.getSize());
consultAttach.setExtensionName(path.substring(path.lastIndexOf('.')));
consultAttach.setAttachUrl(FileUploadUtil.getFullShowUrl(path));
}
然后是service调用 多文件上传的话传数组MultipartFile[] 单个上传的话 去掉for
public void upload(MultipartFile[] attachFiles) {
if(array == null || array.length == 0){
return;
}
for (MultipartFile attachFile : attachFiles) {
try {
uploadMultipartFile (attachFile);
} catch (IOException e) {
StaticLog.error(e, "上传会诊附件失败");
}
}
}
完成