前端上传图片并用Java存到数据库中

1.首先在数据库创建LONGBLOB字段 

2.实体接收类为byte[]

前端上传图片代码

<form id="touxiangshangchuan" action="http://127.0.0.1/user/posts" target="frameName"    enctype="multipart/form-data" method="post">
		<input type="file" name="file" value="修改头像">
		<input class="btn" type="submit" id="anxia" value="上传" onclick="Excea()">
</form>
  <!-- iframename和form的名称相同可以防止提交文件上传后自动跳转 -->
<iframe style="display: none;" frameborder="0" name="frameName"></iframe>

<script>
function Excea(){
  layer.msg('头像修改成功', {
  icon: 1,
  time: 1600//
}, function(){
  location.reload(true)
}); 

微信小程序端上传如下

 shangchuan(){
     var that =this
    wx.chooseImage({
      count: 1, // 一次只能选择一张图片
      sourceType: ['album'], // 从相册选择
      success: function(res) {
          // 将图片上传到服务器
          wx.uploadFile({
              url: app.globalData.user_http+"/user/posts/"+that.data.user_id, // 上传的服务器地址
              filePath: res.tempFilePaths[0], 
              name:'files',
              success: function(res) {
                  // 上传成功,做一些处理
              }
          })
      }
  })
   },

springboot需要打开取消默认文件限制

spring:
#  swagger不兼容配置
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/dianqi?serverTimezone=UTC
      username: root
      password: 123456
#接收文件限制-1为不指定大小
  servlet:
    multipart:
      max-file-size: -1
      max-request-size: -1
server:
  port: 80
#打开mybatis控制台输出
mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

java中接收传输的文件


    @PostMapping(value = "/posts")
    public Map<String, Object> addImg(StandardMultipartHttpServletRequest request,
                                      MultipartFile file, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            byte[] data;
            data = file.getBytes();
            User user = (User) session.getAttribute("user");
            userService.insertOne(data, user.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.put("message", "上传成功");
        return result;
    }

Server层代码

    public void insertOne(byte[] data, Integer user_id) {
        userMapper.insert_touxiang(data, user_id);
    }

Mapper层代码

 void insert_touxiang(@Param("data") byte[] data, @Param("user_id") Integer user_id);

//对应映射文件
    <update id="insert_touxiang">
        UPDATE user
        SET touxiang = #{data, jdbcType=BLOB}
        where id =#{user_id}
    </update>

前端回显用户头像

                controller层

    @GetMapping(value = "/getImgById2")
    public Result getImgById22(HttpSession session,
                               HttpServletResponse response) {
        User user = (User) session.getAttribute("user");
        Integer id = user.getId();
        User data = userService.select_touxiang(id);
        String base64Str = Base64.getEncoder().encodeToString(data.getTouxiang());
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        String zhuanhuan = "data:image/png;base64," + base64Str;
        return Result.success(zhuanhuan);
    }

Service层

    public User select_touxiang(Integer id) {

        return userMapper.select_id(id);
    }

Mapper层

    @Select("select * from user where id = #{niuma}")
    User select_id(Integer id);

前端获取头像直接插入img标签即可

转换后为base64位 后端已经默认加入,也可自行在前端配置在src属性

"data:image/png;base64,"+要放置的base64位图片

  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java项目使用MongoDB,你需要遵循以下步骤: 1. 安装MongoDB:在官网下载MongoDB并按照说明进行安装。 2. 添加MongoDB的Java驱动程序:你可以使用Maven或Gradle添加MongoDB的Java驱动程序。 3. 在Java项目连接MongoDB:使用Java驱动程序连接MongoDB,并在Java代码实现CRUD操作。 4. 创建REST API:将MongoDB数据暴露为REST API,以便从前端应用程序访问。 5. 创建Vue应用程序:使用Vue框架创建前端应用程序,并将其链接到后端REST API。 以下是具体步骤: 1. 安装MongoDB 请参考MongoDB的官方文档进行安装。 2. 添加MongoDB的Java驱动程序 如果你使用Maven,则可以在pom.xml文件添加以下依赖项: ``` <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.1.0</version> </dependency> ``` 如果你使用Gradle,则可以在build.gradle文件添加以下依赖项: ``` implementation 'org.mongodb:mongodb-driver-sync:4.1.0' ``` 3. 在Java项目连接MongoDB 在Java代码连接MongoDB,你需要使用MongoClient类。以下是一个简单的示例: ``` import com.mongodb.client.MongoClients; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoDatabase; public class MongoConnection { private static final String DATABASE_NAME = "mydatabase"; private static final String CONNECTION_STRING = "mongodb://localhost:27017"; public static MongoDatabase getDatabase() { MongoClient mongoClient = MongoClients.create(CONNECTION_STRING); return mongoClient.getDatabase(DATABASE_NAME); } } ``` 此代码创建一个MongoDB客户端对象,并返回指定的数据库对象。 4. 创建REST API 使用Spring Boot创建REST API,并使用MongoDB驱动程序实现CRUD操作。以下是一个简单的示例: ``` @RestController @RequestMapping("/api") public class MyController { @Autowired private MyRepository repository; @GetMapping("/items") public List<Item> getItems() { return repository.findAll(); } @PostMapping("/items") public Item addItem(@RequestBody Item item) { return repository.save(item); } @DeleteMapping("/items/{id}") public void deleteItem(@PathVariable String id) { repository.deleteById(id); } } @Repository public interface MyRepository extends MongoRepository<Item, String> { } ``` 此代码创建一个REST API,用于获取、添加和删除MongoDB的文档。 5. 创建Vue应用程序 使用Vue框架创建前端应用程序,并将其链接到后端REST API。以下是一个简单的示例: ``` <template> <div> <ul> <li v-for="item in items" :key="item.id">{{ item.name }}</li> </ul> <input v-model="newItemName" /> <button @click="addItem">Add</button> </div> </template> <script> import axios from 'axios'; export default { data() { return { items: [], newItemName: '', }; }, created() { this.getItems(); }, methods: { getItems() { axios.get('/api/items').then((response) => { this.items = response.data; }); }, addItem() { axios.post('/api/items', { name: this.newItemName }).then(() => { this.getItems(); }); }, }, }; </script> ``` 此代码创建一个Vue组件,用于获取、添加和删除MongoDB的文档。它使用Axios库发出HTTP请求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值