SpringMVC上传图片或者文件后返回文件服务器地址路径并保存数据库

最近项目的一个需求,用户上传图片

前端先写一个表单:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

        <div style="border: 1px solid red;">
			我是添加一张临时图片得到微信的media_id保存数据库!
			<form action="/MkeyPlus-Interface/API/User/uploadPic" enctype="multipart/form-data" method="post">
				<div style="display: none;">
					<input type="text" value="IMAGE" name="type"/>
				</div>
				上传图片:
				<input type="file" name="uploadFile" onchange="previewImage(this, 'prvid')" multiple="multiple"><br />
				<input type="submit" value="提交" />
			</form>
			<div id="prvid">预览容器</div>
		</div>   

</body>
</html>

这里要注意的点是  enctype="multipart/form-data" 这个表单的文件类型,决定后台入户接收参数

 action层接收文件处理:

/**
     * 资源文件上传,返回一个文件服务器地址
     * @author Libin
     * @date 2018年1月12日 上午10:28:08
     */
    @RequestMapping(value ="/fileUpload.jspx")
    public void uploadFileBackAddress(HttpServletRequest request, HttpServletResponse response) {
      try {
            MultipartFile multipartFile = null;
            if (request instanceof MultipartHttpServletRequest) {
                multipartFile = ((MultipartHttpServletRequest)request).getFile("uploadFile");
            }
            if (null != multipartFile) {
                /**
                 * 项目服务器地址路径
                 */
                String projectServerPath = request.getScheme() + "://"+request.getServerName()+":" +
                                request.getServerPort() + request.getContextPath() + "/upload/";
                /**
                 * 上传文件绝对路径
                 */
                String path = request.getSession().getServletContext().getRealPath("/WEB-INF/upload/");
                /**
                 * 上传文件名
                 */
                String fileName = makeFileName(multipartFile.getOriginalFilename());
                
                File file = new File(path + fileName);
                /**
                 * 判断路径是否存在,如果不存在就创建一个
                 */
                if (!file.getParentFile().exists()) { 
                    
                    file.getParentFile().mkdirs();
                }
                /**
                 * 创建文件
                 */
                multipartFile.transferTo(new File(path + File.separator + fileName));
                /**
                 * 返回服务器文件地址
                 */
                String serverFilePatn = projectServerPath + fileName;
               
            }
            
        }  catch (Exception e) {
            ajaxBackData = this.getAjaxBackDataExceptionStatus(e);
        }
       
    }

最后配置这个文件,但是我当时没有配置呢也可以,各位可以根据自己需求添加

springMVC配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/jee 
    http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc.xsd"
    default-lazy-init="true">
    <context:annotation-config />
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <property name="maxUploadSize" value="10485760000"></property>
        <property name="maxInMemorySize" value="40960"></property>
    </bean>
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- 在web.xml配置detectAllViewResolvers为false不根据ViewResolver接口全扫描,只根据viewResolver标识查找DispatcherServlet的视图解析器 -->
    <bean id="defaultViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <!-- 设置前缀,即视图所在的路径 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 设置后缀,即视图的扩展名 -->
        <property name="suffix" value=".jsp" />
    </bean>
   
</beans>
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
SpringMVC框架中上文件并将相对路径存储到MySQL数据库可以按照以下步骤进行操作: 1. 在前端页面中添加文件功能,可以使用HTML的input标签或者第三方插件如Dropzone.js等。 2. 在后端Controller中添加处理文件的方法,可以使用@RequestParam注解获取上文件。 3. 在处理文件的方法中,将上文件保存服务器本地的指定目录下,可以使用File类的API。 4. 将保存服务器本地的文件的相对路径(相对于Web应用根目录)存储到MySQL数据库中的指定表和字段中,可以使用Spring JDBC Template或者Mybatis等持久化框架。 以下是一个大概的示例代码: 前端HTML页面: ``` <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit" value="Upload"/> </form> ``` 后端Controller: ``` @Controller public class FileUploadController { @RequestMapping(value = "/upload", method = RequestMethod.POST) public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { // 保存文件服务器本地目录下 String filePath = "/uploads/" + file.getOriginalFilename(); File dest = new File(filePath); file.transferTo(dest); // 将文件相对路径存储到MySQL数据库中 String sql = "INSERT INTO file_table (file_path) VALUES (?)"; jdbcTemplate.update(sql, filePath); return "upload_success"; } @Autowired private JdbcTemplate jdbcTemplate; } ``` 其中,`/uploads/`是服务器本地存储文件的相对路径,`file_table`是MySQL数据库中的表名,`file_path`是存储文件相对路径的字段名。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值