天天看點

MultipartFile 上傳、删除檔案到靜态資源伺服器

第一步 首先是要檔案傳輸,類似于檔案傳輸的代碼網上一大把

/**
	 * 上傳檔案到靜态資源伺服器
	 * @param fileType 檔案類型(1:圖檔;2:檔案;3:語音)
	 * @param is 圖檔檔案流
	 * @param filename 檔案名
	 * @param fileDir 檔案目錄(子產品名/功能名;如:"usercenter/user")
	 * @param isResize 是否壓縮圖檔
	 * @param subFileName 子檔案名
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String uploadFileToServer(String fileType, InputStream is, String filename, String fileDir,
			boolean isResize, String subFileName) {
		String res = "";
		HttpURLConnection conn = null;
		// boundary就是request頭和上傳檔案内容的分隔符
		String BOUNDARY = "--------------------------------";
		try {
			String urlType = "";
			if ("1".equals(fileType)) {
				urlType = UPLOAD_IMAGE;
			} else if ("2".equals(fileType)) {
				urlType = UPLOAD_FILE;
			} else if ("3".equals(fileType)) {
				urlType = UPLOAD_VOICE;
			}
			URL url = new URL(getServerUploadUrl() + urlType);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
			OutputStream out = new DataOutputStream(conn.getOutputStream());
			
			// 傳參數
			StringBuffer sb = new StringBuffer();
			sb.append("--").append(BOUNDARY).append("\r\n");
			sb.append("Content-Disposition: form-data; name=\"fileDir\"").append("\r\n").append("\r\n");
			sb.append(fileDir).append("\r\n");
			out.write(sb.toString().getBytes());
			sb = new StringBuffer();
			sb.append("--").append(BOUNDARY).append("\r\n");
			sb.append("Content-Disposition: form-data; name=\"isResize\"").append("\r\n").append("\r\n");
			sb.append(isResize).append("\r\n");
			out.write(sb.toString().getBytes());
			if (StrUtil.isNotEmpty(subFileName)) {
				sb = new StringBuffer();
				sb.append("--").append(BOUNDARY).append("\r\n");
				sb.append("Content-Disposition: form-data; name=\"subFileName\"").append("\r\n").append("\r\n");
				sb.append(subFileName);
				out.write(sb.toString().getBytes());
			}
			
			// 沒有傳入檔案類型,同時根據檔案擷取不到類型,預設采用application/octet-stream
			String contentType = null;
			// contentType非空采用filename比對預設的圖檔類型
			if (filename.endsWith(".png")) {
				contentType = "image/png";
			} else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
				contentType = "image/jpeg";
			} else if (filename.endsWith(".gif")) {
				contentType = "image/gif";
			} else if (filename.endsWith(".ico")) {
				contentType = "image/image/x-icon";
			}
			if (contentType == null || "".equals(contentType)) {
				contentType = "application/octet-stream";
			}
			sb = new StringBuffer();
			sb.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
			sb.append("Content-Disposition: form-data; name=\"" + "file" + "\"; filename=\"" + filename + "\"\r\n");

			sb.append("Content-Type:" + contentType + "\r\n\r\n");
			out.write(sb.toString().getBytes());

			DataInputStream in = new DataInputStream(is);
			int bytes = 0;
			byte[] bufferOut = new byte[1024];
			while ((bytes = in.read(bufferOut)) != -1) {
				out.write(bufferOut, 0, bytes);
			}
			in.close();
			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();
			// 讀取傳回資料
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			res = strBuf.toString();
			reader.close();
			reader = null;
			ObjectMapper mapper = new ObjectMapper();
			Map<String, Object> map = mapper.readValue(res, Map.class);
			if (MapUtil.getInt(map, "result") == 1) {
				return map.get("content").toString();
			} else {
				StaticLog.error("上傳檔案失敗:{}", map.get("errmsg"));
				return null;
			}
		} catch (Exception e) {
			StaticLog.error(e, "上傳檔案失敗");
			return null;
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
	}
           

然後 MultipartFile ,MultipartFile是file的抽象,簡而言之就是前端上傳後端用MultipartFile接受的抽象類

public void uploadMultipartFile ( MultipartFile attachFile) throws IOException {
		String path = uploadFileToServer(attachFile.getInputStream(), attachFile.getOriginalFilename(),
				"xxxx/xxxxx/" , "");
		consultAttach.setAttachName(attachFile.getOriginalFilename());
		consultAttach.setAttachSize(attachFile.getSize());
		consultAttach.setExtensionName(path.substring(path.lastIndexOf('.')));
		consultAttach.setAttachUrl(FileUploadUtil.getFullShowUrl(path));
}
           

然後是service調用 多檔案上傳的話傳數組MultipartFile[]   單個上傳的話 去掉for

public void upload(MultipartFile[] attachFiles) {
  if(array == null || array.length == 0){ 
        return;
    }
    for (MultipartFile attachFile : attachFiles) {
			
				try {
					uploadMultipartFile (attachFile);
				} catch (IOException e) {
					StaticLog.error(e, "上傳會診附件失敗");
					
				}
			}

}
           

完成

接下來是删除

/**
	 * 從靜态資源伺服器删除檔案
	 * @param path
	 */
	public static void deleteFileFromServer(String path) {
		HttpURLConnection urlConn = null;
		try {
			String result = "";
			URL realurl = new URL(getServerUploadUrl() + DELETE_FILE);
			urlConn = (HttpURLConnection) realurl.openConnection();
			urlConn.setDoInput(true); // 設定輸入流采用位元組流
			urlConn.setDoOutput(true); // 設定輸出流采用位元組流
			urlConn.setRequestMethod("POST");
			urlConn.setUseCaches(false); // 設定緩存
			urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			urlConn.setRequestProperty("Charset", "UTF-8");
			urlConn.connect();

			DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
			dos.writeBytes("path=" + path);
			dos.flush();
			dos.close();

			BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
			String line = "";

			while (null != (line = br.readLine())) {
				result += line;
			}
			StaticLog.info("删除檔案成功:{}", result);
			br.close();
		} catch (Exception e) {
			StaticLog.error(e, "删除檔案失敗");
		} finally {
			if (urlConn != null) {
				urlConn.disconnect();
				urlConn = null;
			}
		}
	}
           

完成  删除就沒有寫service方法了