欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

在Java中实现多媒体文件上传和页面展示

最编程 2024-01-17 10:34:19
...
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>实现文件上传</h1>
	<!--enctype="开启多媒体标签" -这一个属性就开启了多媒体文件的上传!! -->
	<form action="http://localhost:8091/file" method="post" 
	enctype="multipart/form-data">
		<input name="fileImage" type="file" />
		<input type="submit" value="提交"/>
	</form>
</body>
</html>

1 编辑FileController --只是引入文件上传的示例

package com.jt.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@RestController
public class FileController {

    /**
     *  MultipartFile 接口作用 主要就是优化了文件上传 API集合
     * 1. 文件上传位置???   D:\JT-SOFT\images
     * 2. 判断一下文件目录是否存在
     * 3. 利用API实现文件上传.
     */
      @RequestMapping("/file")
    public String file(MultipartFile fileImage){
        String fileDir = "D:/JT-SOFT/images";
        File file = new File(fileDir);
        if(!file.exists()){ //文件不存在则创建文件

            file.mkdirs(); //一次性创建多级目录
        }
        //文件信息 = 文件名+文件后缀  ----这里开始真正的利用多媒体文件MultipartFile类型的API-getOriginalFilename获取多媒体文件的全称
        String fileName = fileImage.getOriginalFilename();
        //将文件的整体封装为对象 文件路径/文件名称
        File imageFile = new File(fileDir+"/"+fileName);
        //实现文件上传,将文件字节数组传输到指定的位置. -另一个多媒体文件的API - transferTo上传多媒体文件到本地磁盘位置并保存
        try {  
            fileImage.transferTo(imageFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "文件上传成功!!!!";
    }
}

推荐阅读