项目是api接口,有两个需求。一个是验证签名,签名正确后,才接收上传数据。
首先是服务器接收上传的java代码
public void addCompanyUpLoadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
// response.setHeader("Access-Control-Allow-Origin", "*");
// response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type");
// response.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST,
// DELETE");
String errMsg = "";
String imgPath = "";
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;// request强制转换注意
MultipartFile file = mRequest.getFile("filename");//注意 这个参数一定要filename
errMsg = this.checkFileReasonable(file);
if (!StringUtil.isEmpty(errMsg)) {
throw new DHBizException(errMsg);
}
String path = "";
int filetype = 0;
try {
// 重置文件名
Random random = new Random();
long time = System.currentTimeMillis();
String timePahtStr = String.valueOf(time);
String timeStr = String.valueOf(time) + String.valueOf(random.nextInt(1000000));
String[] originalFileName = file.getOriginalFilename().split("\\.");
String fileName = timeStr + "." + originalFileName[1];
request.setAttribute("filename", file.getOriginalFilename());
filetype = getFileType(originalFileName[1]);
String childPath = "/" + timePahtStr.substring(timePahtStr.length() - 2, timePahtStr.length() - 1) + "/"
+ timePahtStr.substring(timePahtStr.length() - 1, timePahtStr.length());
FileUtils.copyInputStreamToFile(file.getInputStream(),
new File(PropertyUtils.getValue("acexe.imgPath") + childPath, fileName));
path = childPath + "/" + fileName;
// imgPath = PropertyUtils.getValue("img.url") + childPath + "/" + fileName;
imgPath = childPath + "/" + fileName;
} catch (IOException e) {
e.printStackTrace();
}
Map<String, String> map = new HashMap<String, String>();
String guid = UUID.randomUUID().toString();
map.put("url", imgPath);
map.put("path", path);
map.put("guid", guid);
String companyidstr = request.getParameter("CompanyId");
long companyid = Long.parseLong(companyidstr);
CommUploadFiles model = new CommUploadFiles();
model.setCompanyid(companyid);
model.setCreatetime(new Date());
model.setGuid(guid);
model.setFilepath(path);
model.setFiletype(filetype);
uploadFilesService.insertSelective(model);
String jsonString = request.getParameter("Params");
Map<String, Object> mapdata = JsonUtil.readJson2Map(jsonString);
// #region 如果指定的模块传文件,加入特殊处理程序
String modeltype = mapdata.get("modeltype").toString().toLowerCase();
if (StringUtils.isNotBlank(modeltype)) {
specifyProcessModelFile(request, modeltype, guid, companyid,mapdata);
}
// #end region
UploadFilesvo vo = new UploadFilesvo();
vo.setCompanyid(companyid);
vo.setFilepath(guid);
List<UploadFiles> list = compnayuploadFilesService.getList(vo);
map.put("id", list.get(0).getId().toString());
CommResponse commResponse = new CommResponse();
commResponse.setData(map);
commResponse.setSuccess(true);
this.returnData(request, response, commResponse);
}
下面是java请求的代码
private static void httpRequest(String req_url, Map<String, Object> maps, File file) throws Exception {
StringBuffer buffer = new StringBuffer();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(req_url);
MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
for (Entry<String, Object> item : maps.entrySet()) {
entitybuilder.addTextBody(item.getKey(), item.getValue().toString());
}
entitybuilder.addBinaryBody("filename", file, ContentType.APPLICATION_XML, file.getName());
HttpEntity reqEntity = entitybuilder.build();
httpPost.setEntity(reqEntity);
try {
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
int code = response.getStatusLine().getStatusCode();
String info = response.getStatusLine().getReasonPhrase();
if (code != 200) {
throw new Exception(String.valueOf(code) + "&" + info);
}
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
// 将返回的输入流转换成字符串
InputStream inputStream = resEntity.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
System.out.println(buffer.toString());
// 释放资源
inputStream.close();
} finally {
response.close();
}
} finally {
httpclient.close();
}
}