Java url转MultipartFile inputStream转File file转multipartFile

Java url转MultipartFile inputStream转File file转multipartFile
/**
	 * url转MultipartFile
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static MultipartFile urlToMultipartFile(String url) throws Exception {
		File file = null;
		MultipartFile multipartFile = null;
		try {
			HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
			httpUrl.connect();
			file = inputStreamToFile(httpUrl.getInputStream(),"template.png");

			multipartFile = fileToMultipartFile(file);
			httpUrl.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return multipartFile;
	}

	/**
	 * inputStream 转 File
	 * @param ins
	 * @param name
	 * @return
	 * @throws Exception
	 */
	public static File inputStreamToFile(InputStream ins, String name) throws Exception{
		File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
		OutputStream os = new FileOutputStream(file);
		int bytesRead;
		int len = 8192;
		byte[] buffer = new byte[len];
		while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
			os.write(buffer, 0, bytesRead);
		}
		os.close();
		ins.close();
		return file;
	}

	/**
	 * file转multipartFile
	 * @param file
	 * @return
	 */
	public static MultipartFile fileToMultipartFile(File file) {
		FileItemFactory factory = new DiskFileItemFactory(16, null);
		FileItem item=factory.createItem(file.getName(),"text/plain",true,file.getName());
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		try {
			FileInputStream fis = new FileInputStream(file);
			OutputStream os = item.getOutputStream();
			while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new CommonsMultipartFile(item);
	}

你可能感兴趣的:(java)