原文地址
http://blog.csdn.net/xingfeichen/article/details/54378790
1,本地上传代码
- /**
- * 图片上传
- * </p>
- * @param avatarImgPath
- * @return
- */
- private String uploadImgToServer(String avatarImgPath) {
- MultipartEntityBuilder builders = MultipartEntityBuilder.create();
- FileBody imgage = new FileBody(new File(avatarImgPath));
- builders.addPart("img1", imgage);
- HttpEntity reqEntitys = builders.build();
- String results = HttpClientPostUtils
- .postMultiPart("http://192.168.0.221:8080/uploadweb/imgUpload/taskExecuteImg", reqEntitys);
- return results;
- }
- public static String postMultiPart(String url,HttpEntity reqEntity){
- CloseableHttpClient httpclient = HttpClients.createDefault();
- try{
- HttpPost method = new HttpPost(url);
- // MultipartEntity reqEntity = new MultipartEntity();
- method.setEntity(reqEntity);
- CloseableHttpResponse response = httpclient.execute(method);
- try{
- //HttpResponse response=httpClient.execute(method);
- int statusCode = response.getStatusLine().getStatusCode();
- if(statusCode == HttpStatus.SC_OK){
- String body=EntityUtils.toString(response.getEntity());
- return body;
- }}finally{
- response.close();
- }
- }catch(Exception e){
- e.printStackTrace();
- }finally{
- try {
- httpclient.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- return null;
- }
- /**
- * 保存图片到本地
- * </p>
- * @param isDefaultSuffix
- * 是否使用默认后缀名
- * @param path
- * 图片相对路径
- * @param type
- * 图片类型
- * @param request
- * @param response
- * @return
- */
- private String saveImgByType(boolean isDefaultSuffix, String path, String type, MultipartHttpServletRequest request,
- HttpServletResponse response) {
- // if (this.isUploadBlank(request)) {
- // logger.error("upload" + type + " img is null------上传文件为空");
- // return "";
- // }
- logger.info("upload" + type + " img start path: " + path);
- Iterator<String> itr = request.getFileNames();
- MultipartFile mpf = null;
- while (itr.hasNext()) {
- try {
- mpf = request.getFile(itr.next());
- if(mpf.isEmpty()){
- logger.error("upload" + type + " img is null------上传文件为空");
- return null;
- }
- //
- int imgSzie = mpf.getInputStream().available();
- // 获取文件名
- String fileName = mpf.getOriginalFilename();
- if (StringUtils.isBlank(fileName)) {
- logger.error("文件名为空");
- return null;
- }
- // 文件后缀
- String suffix = ".png";
- if(!isDefaultSuffix){
- suffix = fileName.substring(fileName.lastIndexOf("."));
- }
- if (mpf.getSize() / 1000 <= 30000 && mpf.getSize() == imgSzie) {
- // 图片相对路径
- String imgPath = path;
- if (StringUtils.isBlank(imgPath)) {
- imgPath = "files" + File.separator + getImagePath(type) + suffix; // 获得目录下的相对路径
- }
- // 图片绝对路径
- String originalName = MyFileUtil.FILE_PATH + File.separator + imgPath;
- // 保存图片
- MyFileUtil.saveInputStreamToFile(mpf.getInputStream(), originalName);
- // 只针对任务和任务执行的图片进行压缩
- if (originalName.contains(File.separator + IMG_TYPE_TASK + File.separator)
- || originalName.contains(File.separator + IMG_TYPE_TASKEXE + File.separator)) {
- // 获取缩略图路径
- String smallImgPath = getSmallImgName(originalName);
- if (StringUtils.isNotBlank(smallImgPath)) {
- // 临时存储变量
- String tempPath = MyFileUtil.FILE_PATH + File.separator + "temp" + File.separator
- + System.currentTimeMillis() + ".png";
- String parentPath = MyFileUtil.FILE_PATH + File.separator + "temp" + File.separator;
- File parentFile = new File(parentPath);
- if (!(parentFile.exists() && parentFile.isDirectory())) {
- parentFile.mkdir();
- }
- // 按比例缩放(放大缩小)false为缩小,true为放大
- ImageUtils.scale(originalName, tempPath, 4, false);
- ImageHelper.cutCenterImage(tempPath, smallImgPath, ImageUtils.SMALL_IMG_WIDTH,
- ImageUtils.SMALL_IMG_HEIGHT);
- new File(tempPath).deleteOnExit();
- }
- }
- logger.info(imgPath + " 图片上传成功");
- return imgPath;
- } else {
- if (mpf.getSize() != imgSzie) {
- logger.error("#######图片上传失败,服务器获取到图片大小(字节): " + mpf.getSize() + ", 上传图片实际大小(字节): " + imgSzie);
- } else {
- logger.error("单张照片不得超过30M");
- }
- return null;
- }
- } catch (IOException e) {
- logger.error(e.getMessage());
- return null;
- }
- }
- logger.error("没有上传的图片");
- return null;
- }
- /**
- * 获取缩略图路径
- * <br>
- * @param originalName
- * @return
- */
- private String getSmallImgName(String originalName) {
- if (StringUtils.isBlank(originalName))
- return null;
- int index = originalName.lastIndexOf(".");
- String smallPath = "";
- if (index != -1) {
- String prefix = originalName.substring(0, index);
- String suffix = originalName.substring(index + 1);
- smallPath = prefix + "_" + ImageUtils.SMALL_IMG_WIDTH + "x" + ImageUtils.SMALL_IMG_HEIGHT + "." + suffix;
- }
- return smallPath;
- }
- /**
- * @Title: saveInputStreamToFile
- * @Description: 输入流拷贝到文件中
- * @param @param in
- * @param @param destfilePath
- * @return void
- * @throws
- */
- public static void saveInputStreamToFile(InputStream in, String destfilePath) {
- try {
- synchronized(MyFileUtil.class){
- byte[] gif = IOUtils.toByteArray(in);
- FileUtils.writeByteArrayToFile(new File(destfilePath), gif);
- IOUtils.closeQuietly(in);
- logger.info("save pic:" + destfilePath + " success, img size: " + gif.length / 1000);
- }
- } catch (Exception e) {
- logger.error(e.getMessage());
- }
- }