vue前后端分离上传图片

一、先在后端安装multiparty包

npm i multiparty

二、在后端项目中创建一个upload文件

三、在后端项目app.js中配置图片上传的路径

四、在routers文件下index.js中编写上传接口

//引入multiparty包
var multiparty = require('multiparty')
//上传图片
router.post('/uploadImg',(req,res)=>{
  let form = new multiparty.Form()
  form.uploadDir = 'upload'
  form.parse(req,(err,a,imgData)=>{
    res.send({
      code:200,
      path:'http://localhost:3000/' + imgData.file[0].path
    })
  })
})

五、前端图片展示列表

<el-table-column prop="path" label="图片">
        <template slot-scope="scope">
            <el-image 
                style="width: 100px; height: 100px"
                :src="scope.row.path" 
                :preview-src-list="[scope.row.path]">
            </el-image>
        </template>
</el-table-column>

六、前端form表单中点击按钮获取图片进行添加到数据库

<el-form-item label="图片" :label-width="formLabelWidth">
     <el-upload
             class="avatar-uploader"
             action="http://localhost:3000/uploadImg"
             :show-file-list="false"
             :on-success="success"
             :before-upload="beforeAvatarUpload">
          <img v-if="form.path" :src="form.path" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</el-form-item>
 methods: {
    success(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.form.path = res.path
      },
      beforeAvatarUpload(file) {
        const isGIF = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isGIF) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isGIF && isLt2M;
     }
}

七、最后样式

### 图片上传与路径处理最佳实践 #### 1. 前端实现图片上传功能 前端可以利用HTML5中的`<input type="file">`标签来允许用户选择并上传图片。为了提高用户体验,还可以加入一些验证逻辑以确保文件类型和大小符合预期。 ```html <form id="uploadForm"> <label for="imageUpload">Choose image to upload:</label> <input type="file" id="imageUpload" name="imageFile" accept=".jpg,.jpeg,.png"/> <button type="submit">Submit</button> </form> <script> document.getElementById('uploadForm').addEventListener('submit', function(event){ event.preventDefault(); const formData = new FormData(this); fetch('/api/uploadImage', { method: 'POST', body: formData, }) .then(response => response.json()) .then(data => console.log('Success:', data)) .catch(error => console.error('Error:', error)); }); </script> ``` 此代码片段展示了如何创建一个简单的表单用于提交图像文件,并通过JavaScript发送至服务器[^2]。 #### 2. 后端接收图片保存到指定位置 当接收到从前端发来的请求时,后端应该负责解析这些数据并将实际的图片文件存储在一个合适的位置上(比如云储存服务或本地磁盘)。对于Java Spring Boot应用而言,这通常涉及到配置MultipartFile处理器以及设置好相应的目录结构以便于后续读取。 ```java @PostMapping("/uploadImage") public ResponseEntity<Map<String, String>> handleFileUpload(@RequestParam("imageFile") MultipartFile file) throws IOException{ if (file.isEmpty()) { return ResponseEntity.badRequest().build(); } try { byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOAD_DIR + file.getOriginalFilename()); Files.write(path, bytes); Map<String, String> responseBody = Collections.singletonMap("imageUrl", "/images/" + file.getOriginalFilename()); return ResponseEntity.ok().body(responseBody); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } ``` 上述示例说明了怎样编写控制器方法来接受来自客户端的多部分HTTP POST请求,并将上传的文件写入特定的目标文件夹内;同时构建响应体告知前端新图标的相对URL地址[^3]。 #### 3. 返回给前端图片访问链接 一旦成功完成了图片的持久化操作之后,应当向调用方反馈一条消息包含有可以直接用来加载该资源的有效URI字符串。考虑到高并发场景下的效率问题,建议仅记录下指向媒体对象所在物理位置的信息而非直接嵌入整个多媒体流本身作为回应的一部分内容[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值