日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

java 上传文件及预览_SpringBoot上传下载文件及在线预览

發(fā)布時(shí)間:2025/3/11 javascript 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 上传文件及预览_SpringBoot上传下载文件及在线预览 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

SpringBoot上傳下載文件及在線預(yù)覽

今天大概就說說如何使用SpringBoot進(jìn)行上傳和下載以及在線預(yù)覽文件 本篇主要介紹上傳下載的功能,對(duì)于界面就簡單一點(diǎn),大致如下:

一、老規(guī)矩還是先看看小項(xiàng)目的目錄結(jié)構(gòu):

二、添加對(duì)應(yīng)的pom依賴

org.springframework.boot

spring-boot-starter-thymeleaf

org.springframework.boot

spring-boot-starter-web

org.mybatis.spring.boot

mybatis-spring-boot-starter

2.1.1

org.springframework.boot

spring-boot-devtools

runtime

true

mysql

mysql-connector-java

5.1.47

org.projectlombok

lombok

1.18.12

com.alibaba

druid

1.1.21

commons-fileupload

commons-fileupload

1.3.3

三、創(chuàng)建相應(yīng)的配置

spring.application.name=files

server.port=8080

server.servlet.context-path=/files

spring.thymeleaf.cache=false

spring.thymeleaf.suffix=.html

spring.thymeleaf.encoding=UTF-8

spring.thymeleaf.prefix=classpath:/templates/

spring.resources.static-locations=classpath:/templates/,classpath:/static/,file:${upload.dir}

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/files?characterEncoding=UTF-8spring.datasource.username=root

spring.datasource.password=root

mybatis.mapper-locations=classpath:/com/baizhi/mapper/*.xml

mybatis.type-aliases-package=com.baizhi.entity

#控制臺(tái)進(jìn)行打印日志

logging.level.root=info

logging.level.com.baizhi.dao=debug

#上傳和下載文件的路徑

upload.dir=D:/idea_project/java/files/target/classes/static

四、先準(zhǔn)備登陸界面的工作

1、創(chuàng)建實(shí)體類

@Data

@AllArgsConstructor

@NoArgsConstructor

@ToString

@Accessors(chain=true)

public class User {

private Integer id;

private String username;

private String password;

}

2、創(chuàng)建對(duì)應(yīng)的dao層

public interface UserDAO {

User login(User user);

}

3、創(chuàng)建對(duì)應(yīng)的mapper映射文件

select id,username,password

from t_user

where username=#{username}

and password = #{password}

4、創(chuàng)建業(yè)務(wù)層接口及實(shí)現(xiàn)類

public interface UserService {

User login(User user);

}

@Service

@Transactional

public class UserServciceImpl implements UserService{

@Autowired

private UserDAO userDAO;

@Override

@Transactional(propagation = Propagation.SUPPORTS)

public User login(User user) {

return userDAO.login(user);

}

}

5、創(chuàng)建控制器

@Controller

@RequestMapping("user")

@Slf4j

public class UserController {

@Autowired

private UserService userService;

/*** 登錄方法*/

@PostMapping("login")

public String login(User user, HttpSession session){

User userDB = userService.login(user);

if(userDB!=null){

session.setAttribute("user",userDB);

return "redirect:/file/showAll";

}else{

return "redirect:/index";

}

}

}

6、創(chuàng)建登陸界面

用戶登錄

歡迎訪問用戶文件管理系統(tǒng)

username:

password:

7、查看運(yùn)行后對(duì)應(yīng)的界面

五、進(jìn)行主界面的操作

1、創(chuàng)建實(shí)體類

@Data

@AllArgsConstructor

@NoArgsConstructor

@ToString

@Accessors(chain=true)

public class UserFile {

private Integer id;

private String oldFileName;

private String newFileName;

private String ext;

private String path;

private String size;

private String type;

private String isImg;

private Integer downcounts;

private Date uploadTime;

private Integer userId; //用戶外鍵}

2、創(chuàng)建對(duì)應(yīng)的dao層

public interface UserFileDAO {

//根據(jù)登錄用戶id獲取用戶的文件列表 List findByUserId(Integer id);

//保存用戶的文件記錄 void save(UserFile userFile);

//根據(jù)文件id獲取文件信息 UserFile findById(String id);

//根據(jù)id更新下載次數(shù) void update(UserFile userFile);

//根據(jù)id刪除記錄 void delete(String id);

}

3、創(chuàng)建dao層對(duì)應(yīng)的mapper映射文件

select id,oldFileName,newFileName,ext,path,size,type,isImg,downcounts,uploadTime,userId

from t_files

where userId=#{id}

insert into t_files

values (#{id},#{oldFileName},#{newFileName},

#{ext}, #{path},#{size},#{type},

#{isImg},#{downcounts}, #{uploadTime},#{userId})

select id,oldFileName,newFileName,ext,path,size,type,isImg,downcounts,uploadTime,userId

from t_files

where id = #{id}

update t_files set downcounts=#{downcounts} where id=#{id}

delete from t_files where id=#{id}

4、創(chuàng)建對(duì)應(yīng)的業(yè)務(wù)層接口及實(shí)現(xiàn)類

public interface UserFileService {

List findByUserId(Integer id);

void save(UserFile userFile);

UserFile findById(String id);

void update(UserFile userFile);

void delete(String id);

}

@Service

@Transactional

public class UserFileServiceImpl implements UserFileService {

@Autowired

private UserFileDAO userFileDAO;

@Override

public List findByUserId(Integer id) {

return userFileDAO.findByUserId(id);

}

@Override

public void delete(String id) {

userFileDAO.delete(id);

}

@Override

public void update(UserFile userFile) {

userFileDAO.update(userFile);

}

@Override

public UserFile findById(String id) {

return userFileDAO.findById(id);

}

@Override

public void save(UserFile userFile) {

//userFile.setIsImg()? //是否是圖片 解決方案: 當(dāng)類型中含有image時(shí)說明當(dāng)前類型一定為圖片類型 String isImg = userFile.getType().startsWith("image")?"是":"否";

userFile.setIsImg(isImg);

userFile.setDowncounts(0);

userFile.setUploadTime(new Date());

userFileDAO.save(userFile);

}

}

5、創(chuàng)建控制器(重點(diǎn))上傳文件(且保存到i數(shù)據(jù)庫中)

@PostMapping("upload")

public String upload(MultipartFile aaa, HttpSession session) throws IOException {

//獲取上傳文件用戶id User user = (User) session.getAttribute("user");

//獲取文件原始名稱 String oldFileName = aaa.getOriginalFilename();

//獲取文件后綴 String extension = "." + FilenameUtils.getExtension(aaa.getOriginalFilename());

//生成新的文件名稱 String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;

//文件大小 Long size = aaa.getSize();

//文件類型 String type = aaa.getContentType();

//處理根據(jù)日期生成目錄 //String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files"; String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

String dateDirPath = uploadPath + "/files/" + dateFormat;

File dateDir = new File(dateDirPath);

if (!dateDir.exists()) dateDir.mkdirs();

//處理文件上傳 aaa.transferTo(new File(dateDir, newFileName));

//將文件信息放入數(shù)據(jù)庫保存 UserFile userFile = new UserFile();

userFile.setOldFileName(oldFileName).setNewFileName(newFileName).setExt(extension).setSize(String.valueOf(size))

.setType(type).setPath("/files/" + dateFormat).setUserId(user.getId());

userFileService.save(userFile);

return "redirect:/file/showAll";

}下載文件(在線預(yù)覽)

@GetMapping("download")

public void download(String openStyle, String id, HttpServletResponse response) throws IOException {

//獲取打開方式 openStyle = openStyle == null ? "attachment" : openStyle;

//獲取文件信息 UserFile userFile = userFileService.findById(id);

//點(diǎn)擊下載鏈接更新下載次數(shù) if ("attachment".equals(openStyle)) {

userFile.setDowncounts(userFile.getDowncounts() + 1);

userFileService.update(userFile);

}

//根據(jù)文件信息中文件名字 和 文件存儲(chǔ)路徑獲取文件輸入流 String realpath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();

//獲取文件輸入流 FileInputStream is = new FileInputStream(new File(realpath, userFile.getNewFileName()));

//附件下載 response.setHeader("content-disposition", openStyle + ";fileName=" + URLEncoder.encode(userFile.getOldFileName(), "UTF-8"));

//獲取響應(yīng)輸出流 ServletOutputStream os = response.getOutputStream();

//文件拷貝 IOUtils.copy(is, os);

IOUtils.closeQuietly(is);

IOUtils.closeQuietly(os);

}展示所有文件信息

@GetMapping("showAll")

public String findAll(HttpSession session, Model model) {

//在登錄的session中獲取用戶的id User user = (User) session.getAttribute("user");

//根據(jù)用戶id查詢有的文件信息 List userFiles = userFileService.findByUserId(user.getId());

//存入作用域中 model.addAttribute("files", userFiles);

return "showAll";

}刪除文件(及數(shù)據(jù)庫中的)

@GetMapping("delete")

public String delete(String id) throws FileNotFoundException {

//根據(jù)id查詢信息 UserFile userFile = userFileService.findById(id);

//刪除文件 String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();

File file = new File(realPath, userFile.getNewFileName());

if(file.exists())file.delete();//立即刪除

//刪除數(shù)據(jù)庫中記錄 userFileService.delete(id);

return "redirect:/file/showAll";

}返回當(dāng)前的文件列表(json格式數(shù)據(jù))

@GetMapping("findAllJSON")

@ResponseBody

public List findAllJSON(HttpSession session, Model model) {

//在登錄的session中獲取用戶的id User user = (User) session.getAttribute("user");

//根據(jù)用戶id查詢有的文件信息 List userFiles = userFileService.findByUserId(user.getId());

return userFiles;

}

6、創(chuàng)建對(duì)應(yīng)的界面

用戶文件列表頁面

$(function(){

var time;

$("#start").click(function(){

console.log("開啟定時(shí)更新.........");

time = setInterval(function () {

$.get("[[@{/file/findAllJSON}]]", function (res) {

//遍歷 $.each(res, function (index, file) {

$("#" + file.id).text(file.downcounts);

})

});

}, 3000);

});

$("#stop").click(function () {

console.log("關(guān)閉定時(shí)更新");

clearInterval(time);

});

});

歡迎:

文件列表:

開啟定時(shí)更新

結(jié)束定時(shí)更新

ID文件原始名稱文件的新名稱文件后綴存儲(chǔ)路徑文件大小類型是否是圖片下載次數(shù)上傳時(shí)間操作

下載

在線打開

刪除


上傳文件:

六、創(chuàng)建攔截器

public class LoginInterceptor implements HandlerInterceptor {

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

HttpSession session = request.getSession();

Object user = session.getAttribute("user");

if(user!=null) return true;

response.sendRedirect(request.getContextPath()+"/index");

return false;

}

}

七、創(chuàng)建過濾器

@Configuration

public class InterceptorConfig extends WebMvcConfigurationSupport {

@Value("${upload.dir}")

private String upload;

@Override

protected void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(new LoginInterceptor())

.addPathPatterns("/file/**")

.excludePathPatterns("/css/**")

.excludePathPatterns("/js/**");//放行靜態(tài)資源 靜態(tài)資源被認(rèn)為是一個(gè)控制器請(qǐng)求 }

@Override

protected void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/**") //代表以什么樣的請(qǐng)求路徑訪問靜態(tài)資源 .addResourceLocations("classpath:/static/")

.addResourceLocations("classpath:/templates/")

.addResourceLocations("file:"+upload);//本地資源路徑必須放在最上面

}

}

八、進(jìn)行測(cè)試初始化

上傳后

下載

在線預(yù)覽

刪除 變?yōu)槌跏蓟臉幼?有需要源碼的可以聯(lián)系我!

還是要說說我的個(gè)人博客,希望大家多多訪問,謝謝!

總結(jié)

以上是生活随笔為你收集整理的java 上传文件及预览_SpringBoot上传下载文件及在线预览的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。