首页 > 其他分享 >SpringMvc 完整上传文件流程(Ajax请求)头像,图片上传

SpringMvc 完整上传文件流程(Ajax请求)头像,图片上传

时间:2024-09-13 22:22:35浏览次数:3  
标签:String SpringMvc upload System Ajax file println 上传 public

1、config包下的操作

1.1、创建MyWebApplicationInit类

如何创建第一个SpringMvc步骤 以配置类的形式代替xml文件(点击链接查看)

1.2、设置文件大小(自定义)

1.3、创建SpringMvcConfig类 并实现 WebMvcConfigurer接口

@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {
    //视图解析器
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver =
        new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
    //配置WebMvc相关配置,实现接口 WebMvcConfigurer

    //静态资源处理
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    //文件解析器
    @Bean
    public MultipartResolver multipartResolver() {
        StandardServletMultipartResolver multipartResolver =
        new StandardServletMultipartResolver();
        return multipartResolver;
    }

}

1.4、创建AppConfig类 @Import注解导入类

@Configuration
@ComponentScan("")//注解扫描如:com.xxx
@Import({SpringMvcConfig.class, SpringConfig.class})
public class AppConfig {

}

1.5、我的config包下面的类


2、Service包下面的操作

2.1、定义接口FileService类

public interface FileService {
    public String upload(MultipartFile file, HttpServletRequest request) throws Exception;
}

2.2、创建FileServiceImpl并实现FileService接口

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file, HttpServletRequest request) throws Exception {
        //文件上传
        List<String> allowFile= Arrays.asList("jpg","png","gif","bmp");
        //1.获取文件的名
        String filename = file.getOriginalFilename();
        System.out.println("filename:文件名" + filename);
        String suffix = FileUtil.getSuffix(filename);//文件后缀名

 //    if (!allowFile.contains(suffix)){
 //         throw new FileUploadException("文件格式错误");
 //    }

        System.out.println("suffix:文件后缀" + suffix);
        byte[] bytes = file.getBytes();//文件大小
        System.out.println("bytes:文件大小" + bytes.length);

    
        //2.上传路径
        String path = request.getServletContext().getRealPath("/upload");
        FileUtil.writeBytes(bytes, path + "/" + filename);
        File dir = FileUtil.mkdir(path);
        if (!dir.exists()) {
            dir.mkdir();//创建文件夹
        }
        //3.拼接真实文件
        String uuid = IdUtil.randomUUID();
        File uploadFile = new File(path + "/" + uuid + "." + suffix);
        //上传文件
        file.transferTo(uploadFile);
        return uuid+"."+suffix;
    }
}

2.3、我的Service包

3、文件上传操作

3.1、创建xxx.jsp

注意要导入jquery

<script src="${pageContext.request.contextPath}/static/js/jquery.js"></script>>

<form id="userForm" action="${pageContext.request.contextPath}/user/add" method="post" enctype="multipart/form-data">
  姓名<input type="text" name="username"/><br>
  <input type="text" id="avatar" name="avatar"/>
  头像<input type="file" id="file" name="file"/><br>
  预览 <div id="yulan"></div><br>
  <input type="submit" value="上传"/>
</form>

3.2、发送ajax请求

$("#file").change(function () {
    let url = '${pageContext.request.contextPath}/upload';
                 //发送ajax请求
                 $.ajax({
                     url: url,
                     type: "post",//必须是post
                     data: new FormData($("#userForm")[0]),//带有 enctype="multipart/form-data"
                     processData: false,//告诉JQuery不要去处理发送的数据
                     contentType: false,//告诉JQuery不要去处理发送的数据
                     success: function (res) {
                         $("#avatar").val(res);
                         //获取文件上传的图片并且展示
                         let img=$("<img src='${pageContext.request.contextPath}/upload/"+res+"'>")
                         $("#yulan").empty().append(img)

                     },
                     error: function () {
                         alert("上传失败")
                  }
          })
 })

3.3、控制层接收请求

 @RequestMapping(value = "/add",produces="application/json;charset=utf-8")
    public String add(SysUser sysUser) {
        System.out.println(sysUser.getUsername());
        System.out.println(sysUser.getAvatar());
        return "index";
    }
@RequiredArgsConstructor
@RestController
public class FilerController {

    private final FileService fileService;

    @RequestMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        System.out.println("upload.class");
        System.out.println(file);
        return   fileService.upload(file, request);
    }

}

3.4我的包

4、效果图

5、需要导入的jar包

<dependencies>


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.1.11</version>
</dependency>

<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.27</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>


<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.27</version>
</dependency>
</dependencies>

标签:String,SpringMvc,upload,System,Ajax,file,println,上传,public
From: https://blog.csdn.net/or77iu_N/article/details/141634893

相关文章

  • 微信小程序云开发图片上传至云存储,提交到云数据库时的出现的3种文件路径问题
    做本小程序的开发时,考虑到各种因素限制,后台没有自设服务器配置域名,而是使用易上手的原生微信云开发,与之配套的则是云存储、云数据库以及云函数。目前函数处理依旧是在每一个页面的.js文件中,暂未分离迁移至云函数库中。在开发本微信小程序时,有一部分功能是对用户上传的照片进行......
  • Spring,SpringBoot,SpringMvc
    1.Spring是什么?有什么特性?有哪些模块?常用注解?1.1Spring是什么?   一句话概况的话:Spring是一个轻量级,非入侵式的控制反转(IOC)和面向切面(AOP)的框架1.2有什么特性?    Spring特性:        1.AOP编程的支持    Spring提供了面向切面......
  • CNCB 数据上传
    使用CNCB,中国人自己的数据库。因课题需要,进行数据上传,涉及单细胞、bulk、空间等数据。基于此进行整理。Step1创建账户建议使用单位邮箱,进行注册-按照实际情况进行填写。https://www.cncb.ac.cn/(CNCB官网网站)Step2创建BioPriject基于研究信息进行真实填写简略的信息。......
  • 取消上次ajax
    //大数据展示asyncqueryBigData(){this.cancel&&this.cancel();constCancelToken=axios.CancelToken;this.isLoad=true;this.ajaxBasicFinished=false;if(this.pointLayer){this.scene.removeLayer(this.p......
  • 文件上传/下载后台代码
    importcn.hutool.core.io.FileUtil;importcn.hutool.core.util.StrUtil;importcom.example.common.Result;importorg.springframework.web.bind.annotation.*;importorg.springframework.web.multipart.MultipartFile;importjavax.servlet.http.HttpServletRespons......
  • PbootCMS上传图片被压缩怎么解决
    当使用PbootCMS上传图片时,如果图片被压缩导致质量下降或变得模糊,可以通过调整PbootCMS的相关配置来解决这一问题。以下是一些具体的步骤:1.找到配置文件打开PbootCMS安装目录下的config文件夹。找到config.php文件。同时,也需要检查core文件夹下的convention.php文件。2.调......
  • 后台图片上传提示:”上传失败:存储目录创建失败!
    当PbootCMS后台上传图片时提示“上传失败:存储目录创建失败!”时,这通常意味着服务器没有足够的权限来创建必要的目录以存储上传的图片。以下是一些可能的解决方案:1.修改文件夹权限确定文件夹路径:确认上传图片的目标文件夹路径,通常是网站根目录下的static文件夹。更改权限:通过FT......
  • 如何将本地项目上传到GitHub(SSH连接)
    在个人GitHub中新建项目(远程仓库),添加一个README文件,方便后面验证记住这个默认分支,我这里是main,你的可能是master或其他先复制下SSH地址在项目文件夹中右键打开Git命令行初始化本地仓库,同时指定默认分支为main,与远程仓库的main保持一致gitinit-bmain关联本地Git......
  • UDS 诊断 - RequestUpload(请求上传)(0x35)服务
    UDS诊断服务系列文章目录诊断和通信管理功能单元UDS诊断-DiagnosticSessionControl(诊断会话控制)(0x10)服务UDS诊断-ECUReset(ECU重置)(0x11)服务UDS诊断-SecurityAccess(安全访问)(0x27)服务UDS诊断-CommunicationControl(通信控制)(0x28)服务UDS诊断-TesterPresent......
  • 解决PbootCMS上传文件大小限制
    你可以配置PHP和Web服务器以支持大文件上传。具体步骤如下:打开 php.ini 文件并配置基本参数:file_uploads=onupload_tmp_dir=/tmpupload_max_filesize=32Mpost_max_size=32M进一步配置其他参数:max_execution_time=600max_input_time=600memory_l......