java帶參數的文件上傳

項目是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();
		}

	}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章