1.首先我会判断上传的文件格式是不是我要的
public ServiceResult> mutiFileUploadHandle(MultipartFile[] uploadFile) {
ServiceResult> result = new ServiceResult<>();
// 判断文件名是否符合格式
for (MultipartFile file : uploadFile) {
if (file.getSize() > 0) {
String fileName = file.getOriginalFilename();
if (StrUtil.isBlank(fileName)) {
result.setSuccess(false);
result.setMessage("文件不存在,请上传正确的文件");
return result;
}
// 符合以下几种才进行鉴定
if (fileName.toLowerCase().endsWith("jpg") || fileName.toLowerCase().endsWith("png")
|| fileName.toLowerCase().endsWith("bmp")) {
} else {
result.setSuccess(false);
result.setMessage("对不起,目前仅支持jpg、png、bmp格式的图片");
return result;
}
}
}
// 鉴定
List list = new ArrayList<>();
for (MultipartFile file : uploadFile) {
try {
byte[] bytes = file.getBytes();
String encode = Base64.getEncoder().encodeToString(bytes);
list.add(encode);
} catch (IOException e) {
_logger.error(e.toString());
}
}
result.setSuccess(true);
result.setResult(list);
return result;
}
//其次上传图片并返回他的保存路径
/**
* 20190929
* 头像上传
* @param file 上图的图片
* @param flag:
* true:平台上传;
* false:商家上传;
* @return
*/
public String headPicUpload(File file,Integer userId, boolean flag) {
String fileKey = "pic";
Map params = new HashMap();
if (flag) {
//作为条件,如果是平台端的图片
params.put(ConstantsEJS.BRAND, ConstantsEJS.BRAND);
} else {
params.put(ConstantsEJS.SELLER_ID, userId + "");
}
//主要方法
uploadFile(file, fileKey, BRAND_IMAGE_PATH, params);
return result;
}
下面是uploadFile方法
/**
* 上传文件
* @param file 需要上传的文件
* @param fileKey 在网页上< input type=file name=xxx/> xxx就是这里的fileKey
* @param RequestURL 请求的URL
* @param param 传递参数
*/
public void uploadFile(File file, String fileKey, String RequestURL,
Map param) {
if (file == null || (!file.exists())) {
return;
}
requestTime = 0;
long requestTime = System.currentTimeMillis();
long responseTime = 0;
try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(readTimeOut);
conn.setConnectTimeout(connectTimeout);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
// conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = null;
String params = "";
/***
* 以下是用于上传参数
*/
if (param != null && param.size() > 0) {
Iterator it = param.keySet().iterator();
while (it.hasNext()) {
sb = null;
sb = new StringBuffer();
String key = it.next();
String value = param.get(key);
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"")
.append(LINE_END).append(LINE_END);
sb.append(value).append(LINE_END);
params = sb.toString();
dos.write(params.getBytes());
// dos.flush();
}
}
sb = null;
params = null;
sb = new StringBuffer();
Date date = new Date();
String fileName = DateUtil.format(date,"yyyyMMddHHmmss") + UUID.randomUUID().toString().replace("-", "") + ".png";
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition:form-data; name=\"" + fileKey + "\"; filename=\""
+ fileName + "\"" + LINE_END);
sb.append("Content-Type:image/pjpeg" + LINE_END); // 这里配置的Content-type很重要的 ,用于服务器端辨别文件的类型的
sb.append(LINE_END);
params = sb.toString();
sb = null;
dos.write(params.getBytes());
/**上传文件*/
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[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();
responseTime = System.currentTimeMillis();
requestTime = (int) ((responseTime - requestTime) / 1000);
//删除临时文件
file.delete();
if (res == 200) {
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
return;
} else {
return;
}
} catch (MalformedURLException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
}