Browse Source

处理上传文件报系统错误的bug。

yujia 8 years ago
parent
commit
3fac65771f

+ 2 - 2
src/main/java/com/uas/platform/b2c/common/base/api/UploadController.java

@@ -43,9 +43,9 @@ public class UploadController {
         for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
             MultipartFile mf = entity.getValue();
             try {
-                IPicture picture = imageService.save(mf.getOriginalFilename(), mf.getBytes());
+                IPicture picture = imageService.uploadFile(mf);
                 pictures.add(picture);
-            } catch (IOException e) {
+            } catch (Exception e) {
                 e.printStackTrace();
             }
         }

+ 35 - 0
src/main/java/com/uas/platform/b2c/common/base/constant/FileUrl.java

@@ -0,0 +1,35 @@
+package com.uas.platform.b2c.common.base.constant;
+
+/**
+ * 文件服务器的基本链接
+ *
+ * @author yuj 2017-10-12 14:53
+ */
+public class FileUrl {
+
+    /**
+     * 文件上传
+     */
+    public final static String FILE_UPLOAD = "http://10.10.100.200:9999/file/upload";
+
+
+    /**
+     * 文件下载
+     */
+    public final static String FILE_DOWNLOAD = "http://10.10.100.200:9999/file/download";
+
+    /**
+     * 文件删除
+     */
+    public final static String FILE_DELETE = "http://10.10.100.200:9999/file/delete";
+
+    /**
+     * 文件信息
+     */
+    public final static String FILE_INFO = "http://10.10.100.200:9999/file/info";
+
+    /**
+     * 文件额外属性
+     */
+    public final static String FILE_METADATA = "http://10.10.100.200:9999/file/metadata";
+}

+ 2 - 0
src/main/java/com/uas/platform/b2c/common/base/service/ImageService.java

@@ -1,6 +1,7 @@
 package com.uas.platform.b2c.common.base.service;
 
 import com.uas.platform.b2c.common.base.model.IPicture;
+import org.springframework.web.multipart.MultipartFile;
 
 import java.io.File;
 import java.util.List;
@@ -38,4 +39,5 @@ public interface ImageService {
 	 */
 	public IPicture save(String fileName, byte[] fileBytes);
 
+    IPicture uploadFile(MultipartFile mf) throws Exception;
 }

+ 35 - 10
src/main/java/com/uas/platform/b2c/common/base/service/impl/DFSImageServiceImpl.java

@@ -1,20 +1,25 @@
 package com.uas.platform.b2c.common.base.service.impl;
 
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.FilenameUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
+import com.alibaba.fastjson.JSONObject;
 import com.uas.dfs.service.FileClient;
+import com.uas.platform.b2c.common.base.constant.FileUrl;
 import com.uas.platform.b2c.common.base.dao.DBPictureRepository;
 import com.uas.platform.b2c.common.base.model.DBPicture;
 import com.uas.platform.b2c.common.base.model.IPicture;
 import com.uas.platform.b2c.common.base.service.ImageService;
+import com.uas.platform.b2c.core.utils.FastjsonUtils;
+import com.uas.platform.b2c.core.utils.HttpUtils;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.FilenameUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestTemplate;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
 
 @Service
 public class DFSImageServiceImpl implements ImageService {
@@ -22,6 +27,9 @@ public class DFSImageServiceImpl implements ImageService {
 	@Autowired
 	private FileClient fileClient;
 
+	@Autowired
+	private RestTemplate restTemplate;
+
 	@Autowired
 	private DBPictureRepository pictureRepository;
 
@@ -55,7 +63,24 @@ public class DFSImageServiceImpl implements ImageService {
 	@Override
 	public IPicture save(String fileName, byte[] fileBytes) {
 		String fileUrl = fileClient.uploadImage(fileBytes, fileBytes.length, FilenameUtils.getExtension(fileName), null);
+		restTemplate.postForObject(FileUrl.FILE_UPLOAD, null, Object.class, fileBytes);
+
+		restTemplate.postForEntity(FileUrl.FILE_UPLOAD, null, Object.class, fileBytes);
 		return pictureRepository.save(new DBPicture(fileName, fileUrl, com.uas.platform.core.util.FileUtils.getImagePixel(fileBytes)));
 	}
 
+	@Override
+	public IPicture uploadFile(MultipartFile mf) throws Exception {
+		HttpUtils.Response response = HttpUtils.upload(FileUrl.FILE_UPLOAD, mf, null);
+		if (response.getStatusCode() == 200) {
+			JSONObject obj = FastjsonUtils.parseObject(response.getResponseText());
+
+			String fileName = mf.getOriginalFilename();
+			String fileUrl = (String) obj.get("path");
+			return pictureRepository.save(new DBPicture(fileName, fileUrl, com.uas.platform.core.util.FileUtils.getImagePixel(mf.getBytes())));
+		} else {
+			throw new IllegalStateException(response.getResponseText());
+		}
+	}
+
 }

+ 15 - 2
src/main/java/com/uas/platform/b2c/common/base/service/impl/FileServiceImpl.java

@@ -1,12 +1,15 @@
 package com.uas.platform.b2c.common.base.service.impl;
 
 import com.uas.dfs.service.FileClient;
+import com.uas.platform.b2c.common.base.constant.FileUrl;
 import com.uas.platform.b2c.common.base.model.FileUpload;
 import com.uas.platform.b2c.common.base.service.FileService;
 import com.uas.platform.core.exception.IllegalOperatorException;
 import org.apache.commons.io.FilenameUtils;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
+import org.springframework.web.client.RestTemplate;
 import org.springframework.web.multipart.commons.CommonsMultipartFile;
 
 @Service
@@ -15,6 +18,9 @@ public class FileServiceImpl implements FileService {
 	@Autowired
 	private FileClient fileClient;
 
+	@Autowired
+	private RestTemplate restTemplate;
+
 	@Override
 	public String save(FileUpload fileUpload) {
 		CommonsMultipartFile file = fileUpload.getFile();
@@ -31,8 +37,15 @@ public class FileServiceImpl implements FileService {
 	@Override
 	public String save(String fileName, byte[] fileBytes) {
 		try {
-			String path = fileClient.upload(fileBytes, fileBytes.length, FilenameUtils.getExtension(fileName), null);
-			return path;
+//			FilenameUtils.getExtension(fileName);
+//			FileBody fileBody = new FileBody(new File(filePath));
+//			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
+//			builder.addPart("file", fileBody);
+//			HttpEntity reqEntity = builder.build();
+			ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(FileUrl.FILE_UPLOAD, null, String.class, fileBytes);
+			System.out.println(stringResponseEntity.getBody());
+			// String path = fileClient.upload(fileBytes, fileBytes.length, FilenameUtils.getExtension(fileName), null);
+			return null;
 		} catch (Exception e) {
 			e.printStackTrace();
 			throw new IllegalOperatorException("附件上传失败");

+ 298 - 0
src/main/java/com/uas/platform/b2c/core/utils/HttpUtils.java

@@ -0,0 +1,298 @@
+package com.uas.platform.b2c.core.utils;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.http.Consts;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.entity.mime.MultipartEntityBuilder;
+import org.apache.http.entity.mime.content.FileBody;
+import org.apache.http.entity.mime.content.InputStreamBody;
+import org.apache.http.entity.mime.content.StringBody;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.message.BasicNameValuePair;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URLEncoder;
+import java.util.*;
+import java.util.Map.Entry;
+
+public class HttpUtils {
+
+	/**
+	 * 发起POST、PUT请求
+	 * 
+	 * @param params
+	 * @return
+	 * @throws Exception
+	 */
+	public static Response get(String url, Map<String, Object> params) throws Exception {
+		CloseableHttpClient httpClient = HttpClients.createDefault();
+		HttpEntityEnclosingRequestBase request = null;
+		CloseableHttpResponse response = null;
+		try {
+			StringBuilder buf = new StringBuilder(url);
+			if (params != null && !params.isEmpty()) {
+				if (url.indexOf("?") == -1)
+					buf.append("?");
+				else if (!url.endsWith("&"))
+					buf.append("&");
+				Set<Entry<String, Object>> entrys = params.entrySet();
+				for (Entry<String, Object> entry : entrys) {
+					buf.append(entry.getKey()).append("=").append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8")).append("&");
+				}
+			}
+			request = new HttpPost(buf.toString());
+			response = httpClient.execute(request);
+			return Response.getResponse(response);
+		} finally {
+			request.releaseConnection();
+			try {
+				httpClient.close();
+			} catch (IOException e) {
+			}
+			if (response != null) {
+				try {
+					response.close();
+				} catch (IOException e) {
+				}
+			}
+		}
+	}
+
+	/**
+	 * 发起POST、PUT请求
+	 *
+	 * @param datas
+	 * @return
+	 * @throws Exception
+	 */
+	public static Response post(String url, Collection<?> datas) throws Exception {
+		CloseableHttpClient httpClient = HttpClients.createDefault();
+		HttpEntityEnclosingRequestBase request = new HttpPost(url);
+		CloseableHttpResponse response = null;
+		try {
+			if (datas != null && !datas.isEmpty()) {
+				request.setEntity(new StringEntity(FastjsonUtils.toJson(datas), ContentType.create("text/plain", Consts.UTF_8)));
+			}
+			response = httpClient.execute(request);
+			return Response.getResponse(response);
+		} finally {
+			request.releaseConnection();
+			try {
+				httpClient.close();
+			} catch (IOException e) {
+			}
+			if (response != null) {
+				try {
+					response.close();
+				} catch (IOException e) {
+				}
+			}
+		}
+	}
+
+	/**
+	 * 发起POST、PUT请求
+	 *
+	 * @param params
+	 * @return
+	 * @throws Exception
+	 */
+	public static Response post(String url, Map<String, String> params) throws Exception {
+		CloseableHttpClient httpClient = HttpClients.createDefault();
+		HttpEntityEnclosingRequestBase request = new HttpPost(url);
+		CloseableHttpResponse response = null;
+		try {
+			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
+			if (params != null && !params.isEmpty()) {
+				Set<Entry<String, String>> entrys = params.entrySet();
+				for (Entry<String, String> entry : entrys) {
+					nvps.add(new BasicNameValuePair(entry.getKey(), URLEncoder.encode(entry.getValue(), "UTF-8")));
+				}
+			}
+			request.setEntity(new UrlEncodedFormEntity(nvps));
+			response = httpClient.execute(request);
+			return Response.getResponse(response);
+		} finally {
+			request.releaseConnection();
+			try {
+				httpClient.close();
+			} catch (IOException e) {
+			}
+			if (response != null) {
+				try {
+					response.close();
+				} catch (IOException e) {
+				}
+			}
+		}
+	}
+
+	/**
+	 * http上传文件
+	 * 
+	 * @param url
+	 *            请求地址
+	 * @param filePath
+	 *            附件路径
+	 * @param params
+	 *            参数
+	 * @return
+	 * @throws Exception
+	 * @throws IOException
+	 * @throws IllegalStateException
+	 */
+	public static Response upload(String url, String filePath, Map<String, String> params) throws IllegalStateException, IOException,
+			Exception {
+		CloseableHttpClient httpClient = null;
+		CloseableHttpResponse response = null;
+		try {
+			httpClient = HttpClients.createDefault();
+			HttpPost httpPost = new HttpPost(url);
+			FileBody fileBody = new FileBody(new File(filePath));
+			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
+			builder.addPart("file", fileBody);
+			if (params != null) {
+				for (String paramKey : params.keySet()) {
+					StringBody body = new StringBody(params.get(paramKey), ContentType.create("text/plain", Consts.UTF_8));
+					builder.addPart(paramKey, body);
+				}
+			}
+			HttpEntity reqEntity = builder.build();
+			httpPost.setEntity(reqEntity);
+			response = httpClient.execute(httpPost);
+			return Response.getResponse(response);
+		} finally {
+			try {
+				if (response != null) {
+					response.close();
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+			try {
+				if (httpClient != null) {
+					httpClient.close();
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+	}
+
+	/**
+	 * http上传文件
+	 *
+	 * @param url
+	 *            请求地址
+	 * @param multipartFile
+	 *            附件路径
+	 * @param params
+	 *            参数
+	 * @return
+	 * @throws Exception
+	 * @throws IOException
+	 * @throws IllegalStateException
+	 */
+	public static Response upload(String url, MultipartFile multipartFile, Map<String, String> params) throws IllegalStateException, IOException,
+			Exception {
+		CloseableHttpClient httpClient = null;
+		CloseableHttpResponse response = null;
+		try {
+			httpClient = HttpClients.createDefault();
+			HttpPost httpPost = new HttpPost(url);
+			InputStreamBody streamBody = new InputStreamBody(multipartFile.getInputStream(),
+				multipartFile.getOriginalFilename());
+			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
+			builder.addPart("file", streamBody);
+			if (params != null) {
+				for (String paramKey : params.keySet()) {
+					StringBody body = new StringBody(params.get(paramKey), ContentType.create("text/plain", Consts.UTF_8));
+					builder.addPart(paramKey, body);
+				}
+			}
+			HttpEntity reqEntity = builder.build();
+			httpPost.setEntity(reqEntity);
+			response = httpClient.execute(httpPost);
+			return Response.getResponse(response);
+		} finally {
+			try {
+				if (response != null) {
+					response.close();
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+			try {
+				if (httpClient != null) {
+					httpClient.close();
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+	}
+
+	/**
+	 * 下载
+	 * 
+	 * @param url
+	 * @return
+	 * @throws ClientProtocolException
+	 * @throws IOException
+	 */
+	public static InputStream download(String url) throws ClientProtocolException, IOException {
+		CloseableHttpClient httpClient = HttpClients.createDefault();
+		HttpGet httpGet = new HttpGet(url);
+		CloseableHttpResponse response = httpClient.execute(httpGet);
+		return response.getEntity().getContent();
+	}
+
+	public static class Response {
+		private int statusCode;
+		private String responseText;
+
+		public int getStatusCode() {
+			return statusCode;
+		}
+
+		public void setStatusCode(int statusCode) {
+			this.statusCode = statusCode;
+		}
+
+		public String getResponseText() {
+			return responseText;
+		}
+
+		public void setResponseText(String responseText) {
+			this.responseText = responseText;
+		}
+
+		public Response() {
+		}
+
+		public Response(HttpResponse response) throws IllegalStateException, IOException, Exception {
+			this.statusCode = response.getStatusLine().getStatusCode();
+			this.responseText = IOUtils.toString(response.getEntity().getContent());
+		}
+
+		public static Response getResponse(HttpResponse response) throws IllegalStateException, IOException, Exception {
+			if (response != null)
+				return new Response(response);
+			return null;
+		}
+	}
+}