使用Java实现文件的上传以及图片的回显

1.图解实现文件上传的步骤

在这里插入图片描述

2.上传文件的接口MultipartFile接口

MultipartFile是一个接口(abstract interface)
public interface MultipartFile
/**
A representation of an uploaded file received in a multipart request.
其实例对象代表了一个在multipart请求中接收到的待上传文件
The file contents are either stored in memory or temporarily on disk.
而文件的内容要么存储在记忆中要么暂时存储在硬盘中
In either case, the user is responsible for copying file contents to a
在任何一种情况下,使用者都可以复制文件内容到一个
session-level or persistent store as and if desired. The temporary storages
会话级或者持久存储中
will be cleared at the end of request processing.
在请求处理结束时,临时的存储都会被清空
可以把这个类理解成一个代表型的类,
因为其实例往往用来代表要上传的文件
还有一种是做事型的类
实例化该类是为了使用该类的能做某事的方法
有些类既是代表型的又是做事型的

3.login.jsp

<%@ 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>
<base href="http://localhost:8080/SpringMVCDemo03_4/">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>${msg }</h1>
	<form action="user/login.do">
		<p>账号:<input type="text" name="account"></p>
		<p>密码:<input type="password" name="password"></p>
		<p><input type="submit" value="登录"></p>
	</form>
</body>
</html>

4.UserController

package com.zhiyou100.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.zhiyou100.model.User;
import com.zhiyou100.service.UserService;
import com.zhiyou100.service.impl.UserServiceImpl;

@Controller
@RequestMapping("user")
public class UserController {
	private UserService userService = new UserServiceImpl();
	
	@RequestMapping("login.do")
	public String login(User user,HttpServletRequest request,Model model){
		String result = userService.login(user, request.getSession());
		if (result.equals("登录成功")) {
			return "redirect:info.do";
		}else {
			model.addAttribute("msg", result);
			return "forward:/login.jsp";
		}
	}
	@RequestMapping("info.do")
	public String info(){
		return "success";
	}
	@RequestMapping("update.do")
	public String update(User user,@RequestParam("icon") MultipartFile multipartFile,HttpServletRequest request){
		userService.update(user, multipartFile, request.getSession());
		return "redirect:info.do";
	}
}

5. UserServiceImpl

package com.zhiyou100.service.impl;

import java.io.File;

import javax.servlet.http.HttpSession;

import org.springframework.web.multipart.MultipartFile;

import com.zhiyou100.dao.UserDAO;
import com.zhiyou100.dao.impl.UserDAOImpl;
import com.zhiyou100.model.User;
import com.zhiyou100.service.UserService;

public class UserServiceImpl implements UserService{

	private UserDAO userDAO = new UserDAOImpl();
	@Override
	public String login(User user, HttpSession session) {
		if (user.getAccount() == null || user.getAccount().length() == 0) {
			return "账户名不能为空";
		}
		if (user.getPassword() == null || user.getPassword().length() == 0) {
			return "密码不能为空";
		}
		User user2 = userDAO.findByAccount(user.getAccount());
		if (user2 == null) {
			return "账户不存在";
		}
		if (!user.getPassword().equals(user2.getPassword())) {
			
			return "密码错误";
		}
		session.setAttribute("user", user2);
		return "登录成功";
	}
	@Override
	public void update(User user, MultipartFile multipartFile, HttpSession session) {
		
		User user2 =(User) session.getAttribute("user");
		user2 = userDAO.queryById(user2.getId());
		if (user.getPassword() != null && user.getPassword().length() != 0) {
			user2.setPassword(user.getPassword());	
		}
		if (!multipartFile.isEmpty()) {
			try {
				String path = session.getServletContext().getRealPath("img/");
				String fileName=  "";
				fileName+= System.currentTimeMillis();
				fileName+= session.getId();
				fileName+= multipartFile.getOriginalFilename();
				multipartFile.transferTo(new File(path+fileName));
				user2.setHeader(fileName);
			} catch (Exception e) {
			}
		}
		userDAO.update(user2);
		session.setAttribute("user", user2);
	}
}

6. JDBC

package com.zhiyou100.util;

import java.lang.AutoCloseable;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JDBC {
	public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException{
		InputStream is = JDBC.class.getClassLoader().getResourceAsStream("jdbc.properties");
		Properties properties = new Properties();
		properties.load(is);
		String driver = properties.getProperty("driver");
		String url = properties.getProperty("url");
		String user = properties.getProperty("user");
		String password = properties.getProperty("password");
		Class.forName(driver);
		Connection connection = DriverManager.getConnection(url,user,password);
		return connection;
	}
	public static void Close(AutoCloseable ...closeables){
		for (AutoCloseable closeable : closeables) {
			if (closeable!=null) {
				try {
					closeable.close();
				} catch (Exception e) {
					System.out.println("关闭失败");
					e.printStackTrace();
				}
			}
		}
	}
}

7. jdbc.properties

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://127.0.0.1:3306/test2
user = root
password = 123456

8. success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="http://localhost:8080/SpringMVCDemo03_4/">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${user}
	<c:if test="${user.header ==null }">
		<img alt="" src="img/1.png">
	</c:if>
	<c:if test="${user.header !=null }">
		<img alt="" src="img/${user.header }">
	</c:if>
	<hr>
	<p>修改个人信息</p>
	<form action="user/update.do" method="post" enctype="multipart/form-data">
		<!-- 在这里可以不提交id -->
		<p>
			修改密码:<input type="text" name="password">
		</p>
		<p>
			修改头像:<input type="file" name="icon">
		</p>
		<p>
			<button>修改</button>
		</p>
	</form>
</body>
</html>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现视频上传回显,需要涉及前端页面、后端接口以及视频处理等多方面的技术。下面我将从这些方面一步一步介绍具体实现方法。 1. 前端页面 前端页面需要有一个上传视频的功能,可以使用`<input type="file">`标签实现。在上传时,可以通过`FormData`对象将视频文件和一些其他参数一起发送到后端接口。示例代码如下: ```html <template> <div> <input type="file" @change="handleFileUpload"> <button @click="uploadVideo">上传</button> <video v-if="videoUrl" :src="videoUrl" controls></video> </div> </template> <script> export default { data() { return { videoUrl: '' } }, methods: { handleFileUpload(event) { this.videoFile = event.target.files[0] }, async uploadVideo() { const formData = new FormData() formData.append('file', this.videoFile) formData.append('name', 'video') const response = await fetch('/api/upload', { method: 'POST', body: formData }) const data = await response.json() if (data.success) { this.videoUrl = data.videoUrl } } } } </script> ``` 2. 后端接口 后端接口使用SpringBoot框架,需要使用`@RestController`和`@PostMapping`注解来实现视频上传接口。接收到视频文件后,可以使用FFmpeg库来处理视频文件,将视频转换为指定格式或者提取视频的缩略图等。 ```java @RestController public class VideoController { @PostMapping("/api/upload") public ApiResponse uploadVideo(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return ApiResponse.error("上传文件不能为空"); } try { // 保存视频文件并返回视频的URL String videoUrl = saveVideo(file); return ApiResponse.success(videoUrl); } catch (Exception e) { e.printStackTrace(); return ApiResponse.error("上传失败"); } } private String saveVideo(MultipartFile file) throws Exception { String fileName = UUID.randomUUID().toString() + ".mp4"; File dest = new File("uploads/" + fileName); file.transferTo(dest); return "http://localhost:8080/uploads/" + fileName; } } ``` 3. 视频处理 视频处理需要使用FFmpeg库来实现。在SpringBoot项目中,可以使用`ProcessBuilder`来执行FFmpeg命令。下面是一个实现视频转换为MP4格式的示例代码: ```java private void convertToMp4(String inputPath, String outputPath) throws Exception { String command = String.format("ffmpeg -i %s -c:v libx264 -preset slow -crf 22 -c:a aac -b:a 128k -movflags faststart -f mp4 %s", inputPath, outputPath); Process process = new ProcessBuilder(command.split(" ")).redirectErrorStream(true).start(); InputStream inputStream = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } process.waitFor(); reader.close(); inputStream.close(); } ``` 以上是实现视频上传回显的基本步骤,具体实现还需要根据具体需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值