当前位置: 首页 > 工具软件 > vue-django > 使用案例 >

Vue+Django上传图片

吉玉石
2023-12-01

vue

          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="商品图片">
              <input type="file" @change="getImageFile" id="img">
              <img :src="image"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">确认添加</el-button>
            </el-form-item>
          </el-form>
export const test = (params)=>{
    return axios.post(`tool/test`,params)
}
import {
  test,
  ...
} from "../../api/api";
export default {
  data () {
    return {
      image:'',
        form: {

          goods_image: '',

        },
        ...
     }
  },

...
  methods: {

    getImageFile:function(e) {
      let file = e.target.files[0];
      this.form.goods_image = file;
    },
    onSubmit() {
      let formData = new FormData();
      formData.append('goods_image', this.form.goods_image);
      formData.append('id', this.userData.id);
      var configs = {
        headers:{'Content-Type':'multipart/form-data'}
      }
      test(formData, configs).then(response => {
        if(response.data.msg=="success"){
          this.image = 'http://127.0.0.1:8000/media/'+response.data.image
        }
      })
    },
    ...
}

Python

model.py

    testImage=models.ImageField(verbose_name=u'测试',null=True, blank=True,upload_to = 'avatar/')

view.py

def test(request):
    if request.method == 'POST':
        response = {}
        goods_image = request.FILES.get('goods_image')
        userOne = User.objects.get(id = request.POST.get('id', ''))
        userOne.testImage = goods_image
        userOne.save()
    try:
    	# avatar/705728-20160424234825491-384470376_1CaALm3.png
        response['image'] = str(userOne.testImage)
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)

settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

urls.py

    url(r'^media/avatar/(?P<path>.*)$', serve, {'document_root': os.path.join(settings.MEDIA_ROOT,'avatar/')}),

 类似资料: