#文件上传、图片上传、实时预览(无刷新提交表单)的前后端实现(含源码) @FDDLC
发布日期:2021-06-30 21:05:53 浏览次数:3 分类:技术文章

本文共 3308 字,大约阅读时间需要 11 分钟。

一、先修课

 

二、只上传图片(文件)的情况

这种方式最简单,可参考:

 

三、上传图片,并实时预览,且动态修改图片的地址

1、效果速览

 

2、项目结构

 

3、核心代码

a、MyController.java

package cn.fddlc.controller;import cn.fddlc.domain.User;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import java.io.BufferedReader;import java.io.File;import java.io.FileReader;@Controllerpublic class MyController {    @RequestMapping("/")    public String home(){        return "form";    }    @ResponseBody    @RequestMapping("/imgUpload")//用于第1个表单的图片上传    public String imgUpload(MultipartFile myFile) throws Exception{        //获取运行时的类路径(注:其他路径也可在此基础上获得)        String classpath=Thread.currentThread().getContextClassLoader().getResource("/").getPath();        //replace前:webRoot/WEB-INF/classes/;replace后:webRoot/img/        String imgBase=classpath.replace("WEB-INF/classes/","img/");        File imgBaseDir=new File(imgBase);        if(!imgBaseDir.exists())imgBaseDir.mkdirs();//如果图片目录不存在,则创建之        String fileName=myFile.getOriginalFilename();//新文件的名字,可自行添加额外处理        File file=new File(imgBase,fileName);        myFile.transferTo(file);//得到新文件        String src="img/"+fileName;//iframe中img的src值        StringBuilder responseBody=new StringBuilder("
"); //replace前:webRoot/WEB-INF/classes/;replace后:webRoot/WEB-INF/view/iframe.html String iframe=classpath.replace("classes/","view/iframe.html"); BufferedReader bufferedReader=new BufferedReader(new FileReader(iframe)); String curLine; while((curLine=bufferedReader.readLine())!=null){ responseBody.append(curLine).append('\n'); } return responseBody.toString();//把String类型的页面响应给用户 } @ResponseBody//偷个懒;也可自行编写响应页面 @RequestMapping("/submit") public String submit(User user){ return user.toString();//User中加了@Data,会重写toString }}

 

b、form.jsp

<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" %>    
username:
password:
avatar:

 

c、iframe.html

 

接下来是非核心文件——

4、依赖

org.springframework
spring-webmvc
5.3.6
commons-fileupload
commons-fileupload
1.3.3
org.projectlombok
lombok
1.18.8

 

5、web.xml

Archetype Created Web Application
dispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:application.xml
dispatcherServlet
/

 

6、application.xml

 

7、User.java

package cn.fddlc.domain;import lombok.Data;@Data//Lombok注解:免写getter、setter等public class User {    private String username;    private String password;    private String avatar;}

 

四、源码链接

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载地址:https://liuxingchang.blog.csdn.net/article/details/117073051 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:#力扣 LeetCode1800. 最大升序子数组和 @FDDLC
下一篇:#Java:读取全部文件内容到String中 @FDDLC

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月06日 08时17分27秒