当前位置: 首页>>代码示例>>Java>>正文


Java URLConnection.guessContentTypeFromName方法代码示例

本文整理汇总了Java中java.net.URLConnection.guessContentTypeFromName方法的典型用法代码示例。如果您正苦于以下问题:Java URLConnection.guessContentTypeFromName方法的具体用法?Java URLConnection.guessContentTypeFromName怎么用?Java URLConnection.guessContentTypeFromName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.net.URLConnection的用法示例。


在下文中一共展示了URLConnection.guessContentTypeFromName方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: addFile

import java.net.URLConnection; //导入方法依赖的package包/类
public void addFile(String name, File file)
        throws IOException {
    String fileName = file.getName();
    String mimeType = URLConnection.guessContentTypeFromName(fileName);
    println("--" + boundary);
    println("Content-Disposition: form-data; name=\"" + name
                    + "\"; filename=\"" + fileName + "\"");
    println("Content-Type: " + mimeType);
    println("Content-Transfer-Encoding: binary");
    println();
    out.flush();

    try (FileInputStream in = new FileInputStream(file)) {
        byte[] buff = new byte[4096];
        for (int n = in.read(buff); n > -1; n = in.read(buff)) {
            stream.write(buff, 0, n);
        }
    }

    println();
}
 
开发者ID:robbyn,项目名称:nzbupload,代码行数:22,代码来源:Multipart.java

示例2: overwrite

import java.net.URLConnection; //导入方法依赖的package包/类
/**
 * Replace the content of an existing file handle. Requires security to be set.
 * Does not update the filename or MIME type.
 *
 * @param pathname path to the file, can be local or absolute
 * @throws HttpException on error response from backend
 * @throws IOException           on error reading file or network failure
 */
public void overwrite(String pathname) throws IOException {
  if (!config.hasSecurity()) {
    throw new IllegalStateException("Security must be set in order to overwrite");
  }

  File file = Util.createReadFile(pathname);

  String mimeType = URLConnection.guessContentTypeFromName(file.getName());
  RequestBody body = RequestBody.create(MediaType.parse(mimeType), file);

  Response response = Networking.getBaseService()
      .overwrite(handle, config.getPolicy(), config.getSignature(), body)
      .execute();

  Util.checkResponseAndThrow(response);
}
 
开发者ID:filestack,项目名称:filestack-java,代码行数:25,代码来源:FileLink.java

示例3: getImageMimeType

import java.net.URLConnection; //导入方法依赖的package包/类
/**
 * Returns the mime type of the given item.
 */
public String getImageMimeType(FileItem item){
	String mime = "";
	try {
		mime = URLConnection.guessContentTypeFromName(item.getPath());
	} catch (StringIndexOutOfBoundsException e){
		// Not sure the cause of this issue but it occurred on production so handling as blank mime.
	}

	if (mime == null || mime.isEmpty()){
		// Test mime type by loading the image
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(item.getPath(), opt);
		mime = opt.outMimeType;
	}

	return mime;
}
 
开发者ID:ScreamingHawk,项目名称:android-slideshow,代码行数:22,代码来源:FileItemHelper.java

示例4: injectUpload

import java.net.URLConnection; //导入方法依赖的package包/类
/**
		 * Inject a file to upload into the URLConnection and set method to POST.
		 * 
		 * @throws IOException
		 */
		public void injectUpload() throws IOException {
			
			String charset = CHARSET_UTF_8;
			String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.

			try {
				connection.setRequestMethod(HTTP_METHOD_POST);
				connection.setDoOutput(true);
				connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
				
				OutputStream output = connection.getOutputStream();
				PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
				
				// Send binary file.
				writer.append("--" + boundary).append(CRLF);
				writer.append("Content-Disposition: form-data; name=\"" + CONTENT_DISPOSITION_NAME + "\"; filename=\"" + uploadFile.getName() + "\"").append(CRLF);
				
				String mediaType = URLConnection.guessContentTypeFromName(uploadFile.getName());
				if (mediaType != null) {
					writer.append("Content-Type: " + mediaType).append(CRLF);
				}
				
				writer.append("Content-Transfer-Encoding: binary").append(CRLF);
				writer.append(CRLF).flush();
				Files.copy(uploadFile.toPath(), output);
				output.flush(); // Important before continuing with writer
				writer.append(CRLF).flush(); // CRLF is important, indicates end o)f boundary
				
				// End of multipart/form-data
				writer.append("--" + boundary + "--").append(CRLF).flush();
				
			} catch (IllegalStateException | ProtocolException e) {
				// don't inject file, because http connection was already connected, will usually be overwritten later anyways
//				e.printStackTrace();
			}
		}
 
开发者ID:EnFlexIT,项目名称:AgentWorkbench,代码行数:42,代码来源:OIDCAuthorization.java

示例5: guessContentTypeFromFile

import java.net.URLConnection; //导入方法依赖的package包/类
/**
 * Guess Content-Type header from the given file (defaults to "application/octet-stream").
 *
 * @param file The given file
 * @return The guessed Content-Type
 */
public String guessContentTypeFromFile(File file) {
    String contentType = URLConnection.guessContentTypeFromName(file.getName());
    if (contentType == null) {
        return "application/octet-stream";
    } else {
        return contentType;
    }
}
 
开发者ID:ina-foss,项目名称:afp-api-client,代码行数:15,代码来源:ApiClient.java

示例6: downloadOrEditFile

import java.net.URLConnection; //导入方法依赖的package包/类
/**
 * Edit or Download for FileExplorer feature
 *
 * @param applicationName
 * @param containerId
 * @param path
 * @param fileName
 * @param request
 * @param response
 * @param editionMode
 * @throws ServiceException
 * @throws CheckException
 * @throws IOException
 */
private void downloadOrEditFile(final String applicationName, final String containerId, String path,
		final String fileName, HttpServletRequest request, HttpServletResponse response, Boolean editionMode)
		throws ServiceException, CheckException, IOException {

	if (logger.isDebugEnabled()) {
		logger.debug("containerId:" + containerId);
		logger.debug("applicationName:" + applicationName);
		logger.debug("fileName:" + fileName);
	}

	User user = authentificationUtils.getAuthentificatedUser();
	Application application = applicationService.findByNameAndUser(user, applicationName);

	String mimeType = URLConnection.guessContentTypeFromName(fileName);
	String contentDisposition = String.format("attachment; filename=%s", fileName);
	response.setContentType(mimeType);
	response.setHeader("Content-Disposition", contentDisposition);
	if (!editionMode) {
		response.setHeader("Content-Description", "File Transfer");
		response.setContentType("utf-8");
	}

	// We must be sure there is no running action before starting new one
	this.authentificationUtils.canStartNewAction(user, application, locale);
	try (OutputStream stream = response.getOutputStream()) {
		fileService.getFileFromContainer(containerId, "/" + path + "/" + fileName, stream);
		stream.flush(); // commits response!
		stream.close();
	} catch (IOException ex) {
		ex.printStackTrace();
	}
}
 
开发者ID:oncecloud,项目名称:devops-cstack,代码行数:47,代码来源:FileController.java

示例7: upload

import java.net.URLConnection; //导入方法依赖的package包/类
/**
 * Upload a file with specified content type
 * @param file File to upload
 * @param contentType content type of {@code file}
 * @return {@link OwOAction} of type {@link OwOFile}
 *
 * @throws NullPointerException if {@code file} is null
 */
public OwOAction<OwOFile> upload(@NotNull File file, @Nullable String contentType) {
    if(contentType == null) {
        String guessedType = URLConnection.guessContentTypeFromName(file.getName());
        contentType = guessedType == null ? DEFAULT_CONTENT_TYPE : guessedType;
    }

    try {
        return upload(Files.readAllBytes(file.toPath()), file.getName(), contentType);
    } catch (IOException e) {
        return new OwOAction<>(e);
    }
}
 
开发者ID:whats-this,项目名称:owo.java,代码行数:21,代码来源:OwO.java

示例8: guessMimeType

import java.net.URLConnection; //导入方法依赖的package包/类
private String guessMimeType(String fileName) {
    String guess = URLConnection.guessContentTypeFromName(fileName);
    if (guess == null) {
        return "application/octet-stream";
    }
    return guess;
}
 
开发者ID:AviranAbady,项目名称:woodpecker,代码行数:8,代码来源:PostRequest.java

示例9: isVideo

import java.net.URLConnection; //导入方法依赖的package包/类
public static boolean isVideo(String path) {
    String mimeType = URLConnection.guessContentTypeFromName(path);
    return mimeType != null && mimeType.startsWith("video");
}
 
开发者ID:aliyun,项目名称:aliyun-cloudphotos-android-demo,代码行数:5,代码来源:MimeTypeUtil.java

示例10: getMimeTypeFromExtension

import java.net.URLConnection; //导入方法依赖的package包/类
/**
 * @return the mime type (if any) that is associated with the file
 *         extension. Returns null if no corresponding mime type exists.
 */
@CalledByNative
public static String getMimeTypeFromExtension(String extension) {
    return URLConnection.guessContentTypeFromName("foo." + extension);
}
 
开发者ID:lizhangqu,项目名称:chromium-net-for-android,代码行数:9,代码来源:AndroidNetworkLibrary.java

示例11: uploadFileToTransport

import java.net.URLConnection; //导入方法依赖的package包/类
public void uploadFileToTransport(String ChangeID, String TransportID, String filePath, String ApplicationID) throws IOException, CMODataClientException {
    logger.trace(format("Entering 'uploadFileToTransport'. ChangeID: '%s', TransportId: '%s', FilePath: '%s', ApplicationId: '%s'.",
            ChangeID, TransportID, filePath, ApplicationID));
    checkClosed();

    File file = new File(filePath);

    if(!file.canRead()) {
        throw new CMODataClientException(format("Cannot upload file '%s' to transport '%s'. File cannot be read.", file.getAbsolutePath(), TransportID));
    }

    URIBuilder uribuilder = this.client.newURIBuilder(serviceUrl).appendEntitySetSegment("Files");

    URI fileStreamUri = uribuilder.build();

    fileStreamUri = URI.create(fileStreamUri.toString() + "(ChangeID='" + ChangeID + "',TransportID='" + TransportID + "',FileID='" + file.getName() + "',ApplicationID='" + ApplicationID + "')");

    logger.debug(format("File stream URI for uploading file '%s' to transport '%s' for change id '%s': '%s'.",
        file.getAbsolutePath(), ChangeID, TransportID,  fileStreamUri.toASCIIString()));

    ODataResponse createMediaResponse = null;
    try (FileInputStream fileStream = new FileInputStream(file)) {

        ODataMediaEntityUpdateRequest createMediaRequest = this.client.getCUDRequestFactory().getMediaEntityUpdateRequest(fileStreamUri, fileStream);

        createMediaRequest.addCustomHeader("x-csrf-token", getCSRFToken());
        createMediaRequest.setFormat(contentType);

        String mimeType = URLConnection.guessContentTypeFromName(file.getName());

        if (! Strings.isNullOrEmpty(mimeType)) {

            createMediaRequest.setContentType(mimeType);
            logger.debug(format("Assuming mime type '%s' for file '%s'.", mimeType, file.getName()));

        } else {
            logger.warn(format("Cannot derive mimetype from file name '%s'", file.getName()));
        }

        ODataPayloadManager streamManager = createMediaRequest.payloadManager();

        createMediaResponse = streamManager.getResponse();

        checkStatus(createMediaResponse, 204);

        logger.debug(format("File '%s' uploaded to transport '%s' for change id '%s' with application id '%s'.",
                filePath, TransportID, ChangeID, ApplicationID));

    } catch(IOException | CMODataClientException | RuntimeException e) {
        logger.error(format("%s caught while uploading file '%s' to transport '%s' for change id '%s' with application id '%s'.",
                e.getClass().getName(), filePath, TransportID, ChangeID, ApplicationID));
        throw e;
    } finally {
        if(createMediaResponse != null) {
            createMediaResponse.close();
        }
        logger.trace(format("Exiting 'uploadFileToTransport'. ChangeID: '%s', TransportId: '%s', FilePath: '%s', ApplicationId: '%s'.",
                ChangeID, TransportID, filePath, ApplicationID));

    }
}
 
开发者ID:SAP,项目名称:devops-cm-client,代码行数:62,代码来源:CMODataClient.java

示例12: isImageUrl

import java.net.URLConnection; //导入方法依赖的package包/类
public static boolean isImageUrl(String url) {
    String extension = URLConnection.guessContentTypeFromName(url);
    return "jpg".equalsIgnoreCase(extension) || "jpeg".equalsIgnoreCase(extension) || "png".equalsIgnoreCase(extension) || "gif".equalsIgnoreCase(extension) || "bmp".equalsIgnoreCase(extension);
}
 
开发者ID:SalmanTKhan,项目名称:MyAnimeViewer,代码行数:5,代码来源:FileUtils.java

示例13: executeMultipartRequest

import java.net.URLConnection; //导入方法依赖的package包/类
/**
 * This method handles the final upload to the
 * {@link SteemJImageUploadConfig#getSteemitImagesEndpoint()
 * SteemitImagesEndpoint}.
 * 
 * @param accountName
 *            The Steem account used to sign the upload.
 * @param signature
 *            The signature for this upload.
 * @param fileToUpload
 *            The image to upload.
 * @return A URL object that contains the download URL of the image.
 * @throws HttpResponseException
 *             In case the
 *             {@link SteemJImageUploadConfig#getSteemitImagesEndpoint()
 *             SteemitImagesEndpoint} returned an error.
 */
private static URL executeMultipartRequest(AccountName accountName, String signature, File fileToUpload)
        throws IOException {
    NetHttpTransport.Builder builder = new NetHttpTransport.Builder();

    MultipartContent content = new MultipartContent().setMediaType(new HttpMediaType("multipart/form-data")
            .setParameter("boundary", "----WebKitFormBoundaryaAsqCuJ0UrJUS0dz"));

    FileContent fileContent = new FileContent(URLConnection.guessContentTypeFromName(fileToUpload.getName()),
            fileToUpload);

    MultipartContent.Part part = new MultipartContent.Part(fileContent);

    part.setHeaders(new HttpHeaders().set("Content-Disposition",
            String.format("form-data; name=\"image\"; filename=\"%s\"", fileToUpload.getName())));

    content.addPart(part);

    HttpRequest httpRequest = builder.build().createRequestFactory(new HttpClientRequestInitializer())
            .buildPostRequest(new GenericUrl(SteemJImageUploadConfig.getInstance().getSteemitImagesEndpoint() + "/"
                    + accountName.getName() + "/" + signature), content);

    LOGGER.debug("{} {}", httpRequest.getRequestMethod(), httpRequest.getUrl().toURI());

    HttpResponse httpResponse = httpRequest.execute();

    LOGGER.debug("{} {} {} ({})", httpResponse.getRequest().getRequestMethod(),
            httpResponse.getRequest().getUrl().toURI(), httpResponse.getStatusCode(),
            httpResponse.getStatusMessage());

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode response = objectMapper.readTree(httpResponse.parseAsString());

    return new URL(response.get("url").asText());
}
 
开发者ID:marvin-we,项目名称:steemj-image-upload,代码行数:52,代码来源:SteemJImageUpload.java

示例14: handleFileUpload

import java.net.URLConnection; //导入方法依赖的package包/类
/**
 * Handler file upload request(Content-Type: multipart/form-data)
 *
 * @param fileUpload {@link FileUpload}
 * @throws IOException IO exception
 */
private void handleFileUpload(FileUpload fileUpload) throws IOException {

    if (fileUpload.isCompleted()) {

        String contentType = MimeKit.of(fileUpload.getFilename());

        if (contentType == null) {

            contentType = URLConnection.guessContentTypeFromName(fileUpload.getFilename());
        }

        FormFile formFile = new FormFile(fileUpload.getName(), fileUpload.getFilename(), contentType, fileUpload.length());

        if (fileUpload.isInMemory()) {

            formFile.setData(fileUpload.getByteBuf().array());
        } else {

            formFile.setData(Files.readAllBytes(fileUpload.getFile().toPath()));
        }

        if (files == null) {

            files = new HashMap<>();
        }

        files.put(fileUpload.getName(), formFile);
    }
}
 
开发者ID:thundernet8,项目名称:Razor,代码行数:36,代码来源:Request.java


注:本文中的java.net.URLConnection.guessContentTypeFromName方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。