fix img upload function

storage_cloud
nineven 5 years ago
parent 7147e09335
commit be4c0fa661
  1. 69
      fir_client/src/components/FirAppInfosbaseinfo.vue
  2. 40
      fir_client/src/components/FirApps.vue
  3. 76
      fir_client/src/components/FirUserProfileBase.vue
  4. 28
      fir_client/src/restful/index.js
  5. 2
      fir_ser/api/models.py
  6. 6
      fir_ser/api/urls.py
  7. 25
      fir_ser/api/utils/serializer.py
  8. 129
      fir_ser/api/views/localuploads.py
  9. 54
      fir_ser/api/views/login.py
  10. 202
      fir_ser/api/views/uploads.py

@ -32,11 +32,9 @@
<el-form-item label="应用图标"> <el-form-item label="应用图标">
<el-upload <el-upload
class="avatar-uploader" class="avatar-uploader"
:action="getuppicurl" action="#"
:show-file-list="false" :show-file-list="false"
accept=".png , .jpg , .jpeg" accept=".png , .jpg , .jpeg"
:headers="uploadconf.AuthHeaders"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"> :before-upload="beforeAvatarUpload">
<img v-if="currentapp.icon_url" :src="currentapp.icon_url" <img v-if="currentapp.icon_url" :src="currentapp.icon_url"
class="avatar"> class="avatar">
@ -60,7 +58,8 @@
</template> </template>
<script> <script>
import {deleteapp, getappinfos, getapppicurl, getuploadToken, updateapp} from "../restful" import {deleteapp, getappinfos, getapppicurl, uploadimgs, updateapp, getuploadurl} from "../restful"
import { uploadaliyunoss, uploadlocalstorage, uploadqiniuoss} from "../utils";
export default { export default {
name: "FirAppInfosbaseinfo", name: "FirAppInfosbaseinfo",
@ -69,9 +68,54 @@
currentapp: {}, currentapp: {},
imageUrl: "", imageUrl: "",
uploadconf:{}, uploadconf:{},
uploadprocess:0
} }
}, },
methods: { methods: {
updateimgs(certinfo){
uploadimgs(data => {
if (data.code === 1000) {
// eslint-disable-next-line no-console
console.log(data.data);
this.$message.success('上传成功');
this.updateinfo();
}else {
this.$message.error('更新失败');
}
},{'methods':'PUT','data':{'certinfo':certinfo}});
},
uploadtostorage(file,certinfo){
if(certinfo.storage === 1){
// eslint-disable-next-line no-unused-vars,no-unreachable
uploadqiniuoss(file,certinfo,this,res=>{
this.updateimgs(certinfo);
},process=>{
this.uploadprocess = process;
})
}else if(certinfo.storage === 2){
// eslint-disable-next-line no-unused-vars
uploadaliyunoss(file,certinfo,this,res=>{
this.updateimgs(certinfo);
},process=>{
this.uploadprocess = process;
});
}else {
//
certinfo.upload_url = getuploadurl();
// eslint-disable-next-line no-unused-vars,no-unreachable
uploadlocalstorage(file,certinfo,this,res=>{
this.updateimgs(certinfo);
},process=>{
this.uploadprocess = process;
})
}
},
delApp() { delApp() {
//APP //APP
this.$confirm('确认删除 ' + this.currentapp.name + ' ?') this.$confirm('确认删除 ' + this.currentapp.name + ' ?')
@ -138,27 +182,20 @@
} }
}); });
}, },
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
this.$message({
message: '应用图标上传成功',
type: 'success'
});
this.updateinfo();
},
beforeAvatarUpload(file) { beforeAvatarUpload(file) {
const isLt2M = file.size / 1024 / 1024 < 2; const isLt2M = file.size / 1024 / 1024 < 2;
if(file.type === 'image/jpeg' || file.type === 'image/png'|| file.type === 'image/jpg'){ if(file.type === 'image/jpeg' || file.type === 'image/png'|| file.type === 'image/jpg'){
if (isLt2M) { if (isLt2M) {
// return true; // return true;
getuploadToken(data => { uploadimgs(data => {
if (data.code === 1000) { if (data.code === 1000) {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log(data.data) console.log(data.data);
let certinfo=data.data;
this.uploadtostorage(file,certinfo);
} }
},{'methods':false,'data':{'app_id':this.currentapp.app_id,'upload_key':file.name}}); },{'methods':false,'data':{'app_id':this.currentapp.app_id,'upload_key':file.name,'ftype':'app'}});
} }
else{ else{
this.$message.error('上传头像图片大小不能超过 2MB!'); this.$message.error('上传头像图片大小不能超过 2MB!');

@ -268,15 +268,12 @@
<el-col style="width: 33%;height: 460px "> <el-col style="width: 33%;height: 460px ">
<div class=" app-animator appdownload"> <div class=" app-animator appdownload">
<div class=" card app card-ios" style="padding: 0"> <div class=" card app card-ios" style="padding: 0">
<!-- :action="uploadconf.UploadUrl"-->
<el-upload <el-upload
:on-success="handleAvataruploadsuccess"
drag drag
:show-file-list="false" :show-file-list="false"
:before-upload="beforeAvatarUpload" :before-upload="beforeAvatarUpload"
accept=".ipa , .apk" accept=".ipa , .apk"
:headers="uploadconf.AuthHeaders"
action="#" action="#"
multiple> multiple>
<i class="el-icon-upload" style="color: #fff"></i> <i class="el-icon-upload" style="color: #fff"></i>
@ -375,14 +372,13 @@
</template> </template>
<script> <script>
import {getapps, deleteapp,getuploadToken} from "../restful"; import {getapps, deleteapp,analyseApps,getuploadurl} from "../restful";
import {getScrollHeight,getScrollTop,getWindowHeight,getappinfo,uploadqiniuoss,dataURLtoFile,uploadaliyunoss,uploadlocalstorage} from "../utils"; import {getScrollHeight,getScrollTop,getWindowHeight,getappinfo,uploadqiniuoss,dataURLtoFile,uploadaliyunoss,uploadlocalstorage} from "../utils";
export default { export default {
name: "FirApps", name: "FirApps",
data() { data() {
return { return {
uploadconf: {"UploadUrl": ""},
analyseappinfo:{'appname':'','short':'','changelog':''}, analyseappinfo:{'appname':'','short':'','changelog':''},
keysearch: '', keysearch: '',
searchfromtype: '', searchfromtype: '',
@ -412,7 +408,7 @@
this.uploadsuccess +=1; this.uploadsuccess +=1;
if(this.uploadsuccess === 2){ if(this.uploadsuccess === 2){
this.$message.success(file.name + '上传成功'); this.$message.success(file.name + '上传成功');
getuploadToken(data => { analyseApps(data => {
if (data.code === 1000) { if (data.code === 1000) {
let app_uuid = this.analyseappinfo.app_uuid; let app_uuid = this.analyseappinfo.app_uuid;
this.closeUpload(); this.closeUpload();
@ -431,7 +427,7 @@
this.uploadsuccess +=1; this.uploadsuccess +=1;
if(this.uploadsuccess === 2){ if(this.uploadsuccess === 2){
this.$message.success(file.name + '上传成功'); this.$message.success(file.name + '上传成功');
getuploadToken(data => { analyseApps(data => {
if (data.code === 1000) { if (data.code === 1000) {
let app_uuid = this.analyseappinfo.app_uuid; let app_uuid = this.analyseappinfo.app_uuid;
this.closeUpload(); this.closeUpload();
@ -447,13 +443,13 @@
}else { }else {
// //
certinfo.upload_url = this.uploadconf.UploadUrl; certinfo.upload_url = getuploadurl();
// eslint-disable-next-line no-unused-vars,no-unreachable // eslint-disable-next-line no-unused-vars,no-unreachable
uploadlocalstorage(file,certinfo,this,res=>{ uploadlocalstorage(file,certinfo,this,res=>{
this.uploadsuccess +=1; this.uploadsuccess +=1;
if(this.uploadsuccess === 2){ if(this.uploadsuccess === 2){
this.$message.success(file.name + '上传成功'); this.$message.success(file.name + '上传成功');
getuploadToken(data => { analyseApps(data => {
if (data.code === 1000) { if (data.code === 1000) {
let app_uuid = this.analyseappinfo.app_uuid; let app_uuid = this.analyseappinfo.app_uuid;
this.closeUpload(); this.closeUpload();
@ -470,7 +466,7 @@
}, },
getuploadtoken(loading){ getuploadtoken(loading){
getuploadToken(data =>{ analyseApps(data =>{
if(data.code === 1000){ if(data.code === 1000){
this.analyseappinfo.short = data.data.short; this.analyseappinfo.short = data.data.short;
this.analyseappinfo.domain_name = data.data.domain_name; this.analyseappinfo.domain_name = data.data.domain_name;
@ -608,10 +604,7 @@
if(!upload_domain){ if(!upload_domain){
upload_domain=location.origin; upload_domain=location.origin;
} }
this.uploadconf = {
"UploadUrl": upload_domain+"/api/v1/fir/server/upload",
"AuthHeaders": {"Authorization": this.$cookies.get("auth_token")}
};
// this.$store.dispatch('doucurrentapp', {'firapps':1}); // this.$store.dispatch('doucurrentapp', {'firapps':1});
} else { } else {
@ -620,24 +613,7 @@
}, parms); }, parms);
}, },
beforeAvatarUpload(file){
// eslint-disable-next-line no-unused-vars
handleAvataruploadsuccess(response, file, fileList) {
if(response.code === 1000){
this.$message.success(file.name + '上传成功');
}else {
this.$message.error(file.name + '上传失败,'+response.msg);
}
for (let x = 0; x < fileList.length; x++) {
if (file.name === fileList[x].name) {
fileList.splice(x, 1)
}
}
this.uploadflag = true;
this.getappsFun({});
},beforeAvatarUpload(file){
const loading = this.$loading({ const loading = this.$loading({
lock: true, lock: true,
text: '应用解析中', text: '应用解析中',

@ -4,11 +4,9 @@
<el-upload <el-upload
class="avatar-uploader" class="avatar-uploader"
:action="getuppicurl" action="#"
:show-file-list="false" :show-file-list="false"
accept=".png , .jpg , .jpeg" accept=".png , .jpg , .jpeg"
:headers="uploadconf.AuthHeaders"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"> :before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar"> <img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i> <i v-else class="el-icon-plus avatar-uploader-icon"></i>
@ -54,7 +52,8 @@
</template> </template>
<script> <script>
import { userinfos,getuserpicurl} from '../restful'; import {userinfos, getuserpicurl, uploadimgs, getuploadurl} from '../restful';
import {uploadaliyunoss, uploadlocalstorage, uploadqiniuoss} from "../utils";
export default { export default {
name: "FirUserProfile", name: "FirUserProfile",
@ -66,6 +65,49 @@
} }
}, },
methods: { methods: {
updateimgs(certinfo){
uploadimgs(data => {
if (data.code === 1000) {
// eslint-disable-next-line no-console
console.log(data.data);
this.$message.success('上传成功');
this.updateUserInfo({"methods":false});
}else {
this.$message.error('更新失败');
}
},{'methods':'PUT','data':{'certinfo':certinfo}});
},
uploadtostorage(file,certinfo){
if(certinfo.storage === 1){
// eslint-disable-next-line no-unused-vars,no-unreachable
uploadqiniuoss(file,certinfo,this,res=>{
this.updateimgs(certinfo);
},process=>{
this.uploadprocess = process;
})
}else if(certinfo.storage === 2){
// eslint-disable-next-line no-unused-vars
uploadaliyunoss(file,certinfo,this,res=>{
this.updateimgs(certinfo);
},process=>{
this.uploadprocess = process;
});
}else {
//
certinfo.upload_url = getuploadurl();
// eslint-disable-next-line no-unused-vars,no-unreachable
uploadlocalstorage(file,certinfo,this,res=>{
this.updateimgs(certinfo);
},process=>{
this.uploadprocess = process;
})
}
},
updateUserInfo(datainfo){ updateUserInfo(datainfo){
userinfos(data=>{ userinfos(data=>{
if(data.code === 1000){ if(data.code === 1000){
@ -79,28 +121,26 @@
} }
}else { }else {
this.$message.error("更新失败") this.$message.error("更新失败")
} }
},datainfo) },datainfo)
}, },
update_name(){ update_name(){
this.updateUserInfo({"methods":'PUT','data':{"first_name":this.userinfo.first_name}}); this.updateUserInfo({"methods":'PUT','data':{"first_name":this.userinfo.first_name}});
},
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
this.$message({
message: '应用图标上传成功',
type: 'success'
});
this.updateUserInfo({"methods":false});
}, },
beforeAvatarUpload(file) { beforeAvatarUpload(file) {
const isLt2M = file.size / 1024 / 1024 < 2; const isLt2M = file.size / 1024 / 1024 < 2;
if(file.type === 'image/jpeg' || file.type === 'image/png'|| file.type === 'image/jpg'){ if(file.type === 'image/jpeg' || file.type === 'image/png'|| file.type === 'image/jpg'){
if (isLt2M) { if (isLt2M) {
return true; uploadimgs(data => {
if (data.code === 1000) {
// eslint-disable-next-line no-console
console.log(data.data);
let certinfo=data.data;
this.uploadtostorage(file,certinfo);
}
},{'methods':false,'data':{'app_id':this.userinfo.uid,'upload_key':file.name,'ftype':'head'}});
return false;
} }
else{ else{
this.$message.error('上传头像图片大小不能超过 2MB!'); this.$message.error('上传头像图片大小不能超过 2MB!');
@ -125,10 +165,6 @@
}, mounted() { }, mounted() {
this.autoSetInfoIndex(); this.autoSetInfoIndex();
this.updateUserInfo({"methods":false}); this.updateUserInfo({"methods":false});
this.uploadconf = {
"AuthHeaders": {"Authorization": this.$cookies.get("auth_token")}
};
}, watch: { }, watch: {
'$store.state.userInfoIndex': function () { '$store.state.userInfoIndex': function () {
this.autoSetInfoIndex(); this.autoSetInfoIndex();

@ -581,12 +581,17 @@ export function getapppicurl(app_id) {
return USERSEVER + '/apps/' + app_id return USERSEVER + '/apps/' + app_id
} }
export function getuploadurl() {
return USERSEVER + '/upload'
}
/**获取上传token */
export function getuploadToken(callBack, params, load = true) { /**分析应用并获取app上传token */
export function analyseApps(callBack, params, load = true) {
getData( getData(
params.methods, params.methods,
USERSEVER + '/qiniuupload' , USERSEVER + '/analyse' ,
params.data, params.data,
data => { data => {
callBack(data); callBack(data);
@ -613,6 +618,7 @@ export function getdownloadurl(callBack, params, load = true) {
); );
} }
/**上传文件到服务器 */
export function uploadstorage(certinfo,file,successCallback,processCallback) { export function uploadstorage(certinfo,file,successCallback,processCallback) {
let config = { let config = {
@ -639,3 +645,19 @@ export function uploadstorage(certinfo,file,successCallback,processCallback) {
}); });
} }
/**获取文件上传token */
export function uploadimgs(callBack, params, load = true) {
getData(
params.methods,
USERSEVER + '/upload',
params.data,
data => {
callBack(data);
},
load,
true,
true
);
}

@ -32,7 +32,7 @@ class UserInfo(AbstractUser):
# password = models.CharField('password', max_length=128, # password = models.CharField('password', max_length=128,
# help_text=mark_safe('''<a class='btn-link' href='set_password'>重置密码</a>''')) # help_text=mark_safe('''<a class='btn-link' href='set_password'>重置密码</a>'''))
head_img = models.CharField(max_length=256, default='/files/imgs/head_img.jpeg', head_img = models.CharField(max_length=256, default='head_img.jpeg',
verbose_name="个人头像") verbose_name="个人头像")
role_choices = ((0, '普通会员'), (1, 'VIP'), (2, 'SVIP'), (3, '管理员')) role_choices = ((0, '普通会员'), (1, 'VIP'), (2, 'SVIP'), (3, '管理员'))
role = models.SmallIntegerField(choices=role_choices, default=0, verbose_name="角色") role = models.SmallIntegerField(choices=role_choices, default=0, verbose_name="角色")

@ -20,9 +20,8 @@ from api.views.login import LoginView,UserInfoView
from api.views.logout import LogoutView from api.views.logout import LogoutView
from api.views.captcha import CaptchaView from api.views.captcha import CaptchaView
from api.views.apps import AppsView,AppInfoView,AppReleaseinfoView from api.views.apps import AppsView,AppInfoView,AppReleaseinfoView
from api.views.localuploads import UploadView,UploadImgView
from api.views.download import ShortDownloadView from api.views.download import ShortDownloadView
from api.views.uploads import OssUploadView from api.views.uploads import AppAnalyseView,UploadView
# router=DefaultRouter() # router=DefaultRouter()
@ -37,8 +36,7 @@ urlpatterns = [
re_path("^apps/(?P<app_id>\w+)", AppInfoView.as_view()), re_path("^apps/(?P<app_id>\w+)", AppInfoView.as_view()),
re_path("^appinfos/(?P<app_id>\w+)/(?P<act>\w+)", AppReleaseinfoView.as_view()), re_path("^appinfos/(?P<app_id>\w+)/(?P<act>\w+)", AppReleaseinfoView.as_view()),
re_path("^upload$",UploadView.as_view()), re_path("^upload$",UploadView.as_view()),
re_path("^img/upload$",UploadImgView.as_view()),
re_path("^userinfo",UserInfoView.as_view()), re_path("^userinfo",UserInfoView.as_view()),
re_path("^short/(?P<short>\w+)$", ShortDownloadView.as_view()), re_path("^short/(?P<short>\w+)$", ShortDownloadView.as_view()),
re_path("^qiniuupload$", OssUploadView.as_view()), re_path("^analyse$", AppAnalyseView.as_view()),
] ]

@ -2,16 +2,12 @@ from rest_framework import serializers
from api import models from api import models
from api.utils.app.apputils import bytes2human from api.utils.app.apputils import bytes2human
from api.utils.TokenManager import DownloadToken from api.utils.TokenManager import DownloadToken
from api.utils.storage.storage import Storage
import os import os
token_obj = DownloadToken() token_obj = DownloadToken()
class UserInfoSerializer(serializers.ModelSerializer): class UserInfoSerializer(serializers.ModelSerializer):
# gender = serializers.SerializerMethodField(source="get_gender_display")
# def get_gender(self, obj):
# return obj.gender
class Meta: class Meta:
model = models.UserInfo model = models.UserInfo
@ -20,7 +16,8 @@ class UserInfoSerializer(serializers.ModelSerializer):
fields=["username","uid","qq","mobile","job","email","domain_name","last_login","first_name",'head_img'] fields=["username","uid","qq","mobile","job","email","domain_name","last_login","first_name",'head_img']
head_img = serializers.SerializerMethodField() head_img = serializers.SerializerMethodField()
def get_head_img(self,obj): def get_head_img(self,obj):
return "/".join([obj.domain_name, obj.head_img]) storage = Storage(obj)
return storage.get_download_url(obj.head_img)
class AppsSerializer(serializers.ModelSerializer): class AppsSerializer(serializers.ModelSerializer):
@ -63,14 +60,6 @@ class AppsSerializer(serializers.ModelSerializer):
"binary_url":master_release_obj.binary_url, "binary_url":master_release_obj.binary_url,
} }
download_url = ""
# if self.context.get("storage", None) and self.context.get("storage") != "undefined":
# if obj.type == 0:
# apptype = '.apk'
# else:
# apptype = '.ipa'
# storage = self.context.get("storage", None)
# download_url = storage.get_download_url(master_release_obj.release_id+apptype)
download_token = token_obj.make_token(master_release_obj.release_id,600) download_token = token_obj.make_token(master_release_obj.release_id,600)
datainfo["download_token"] = download_token datainfo["download_token"] = download_token
@ -101,14 +90,6 @@ class AppReleaseSerializer(serializers.ModelSerializer):
def get_download_token(self,obj): def get_download_token(self,obj):
download_url=''
# if obj.release_type == 0:
# apptype = '.apk'
# else:
# apptype = '.ipa'
# if self.context.get("storage", None) and self.context.get("storage") != "undefined":
# storage = self.context.get("storage", None)
# download_url = storage.get_download_url(obj.release_id + apptype)
download_token = token_obj.make_token(obj.release_id, 600) download_token = token_obj.make_token(obj.release_id, 600)
return download_token return download_token

@ -1,129 +0,0 @@
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# project: 3月
# author: liuyu
# date: 2020/3/6
from rest_framework.views import APIView
from api.utils.response import BaseResponse
from api.utils.auth import ExpiringTokenAuthentication
from api.utils.app.randomstrings import make_from_user_uuid
from rest_framework.response import Response
from fir_ser import settings
from api.utils.TokenManager import DownloadToken
import os,json
class UploadView(APIView):
'''
上传文件接口
'''
authentication_classes = [ExpiringTokenAuthentication, ]
# parser_classes = (MultiPartParser,)
def post(self, request,*args,**kwargs):
res = BaseResponse()
# 获取多个file
files = request.FILES.getlist('file', None)
certinfo = request.data.get('certinfo', None)
try:
certinfo = json.loads(certinfo)
if not certinfo:
res.msg = "token 校验失败"
res.code = 1006
return Response(res.dict)
except Exception as e:
print(e)
res.msg = "token 校验失败"
res.code = 1006
return Response(res.dict)
token_obj = DownloadToken()
if token_obj.verify_token(token=certinfo.get("upload_token",None),release_id=certinfo.get("upload_key",None)):
if not files:
res.msg="文件不存在"
for file_obj in files:
# 将文件缓存到本地后上传
print(file_obj.name)
try:
app_type = file_obj.name.split(".")[-1]
if app_type != "apk" and app_type != "ipa" and app_type != 'png' :
raise TypeError
except Exception as e:
print(e)
res.code = 1003
res.msg = "错误的类型"
return Response(res.dict)
random_file_name = make_from_user_uuid(request.user)
# random_file_name = certinfo.get("upload_key",None)
local_file = os.path.join(settings.MEDIA_ROOT,certinfo.get("upload_key",random_file_name))
# 读取传入的文件
try:
destination = open(local_file, 'wb+')
for chunk in file_obj.chunks():
destination.write(chunk)
destination.close()
except Exception as e:
res.code = 1003
res.msg = "数据写入失败"
return Response(res.dict)
# try:
# AnalyzeUtil("%s"%(random_file_name+"."+app_type),request)
# except Exception as e:
# res.code = 1003
# res.msg = "应用解析失败"
# return Response(res.dict)
else:
res.msg = "token 校验失败"
res.code = 1006
return Response(res.dict)
class UploadImgView(APIView):
'''
上传图片接口
'''
authentication_classes = [ExpiringTokenAuthentication, ]
def post(self, request):
res = BaseResponse()
# 获取多个file
files = request.FILES.getlist('file', None)
uid = request.data.get("uid",None)
print(uid)
for file_obj in files:
# 将文件缓存到本地后上传
try:
app_type = file_obj.name.split(".")[-1]
if app_type in ['png','jpeg','jpg']:
#上传图片
pass
else:
raise
except Exception as e:
res.code = 1003
res.msg = "错误的类型"
return Response(res.dict)
random_file_name = make_from_user_uuid(request.user)
local_file = os.path.join(settings.MEDIA_ROOT,"apps","%s"%(random_file_name+"."+app_type))
# 读取传入的文件
try:
destination = open(local_file, 'wb+')
for chunk in file_obj.chunks():
# 写入本地文件
destination.write(chunk)
destination.close()
except Exception as e:
res.code = 1003
res.msg = "数据写入失败"
return Response(res.dict)
return Response(res.dict)

@ -41,7 +41,8 @@ class LoginView(APIView):
now = datetime.datetime.now() now = datetime.datetime.now()
Token.objects.update_or_create(user=user, defaults={"access_token": key, "created": now}) Token.objects.update_or_create(user=user, defaults={"access_token": key, "created": now})
user_info = UserInfo.objects.get(pk=user.pk) user_info = UserInfo.objects.get(pk=user.pk)
serializer = UserInfoSerializer(user_info)
serializer = UserInfoSerializer(user_info,)
data = serializer.data data = serializer.data
response.msg = "验证成功!" response.msg = "验证成功!"
@ -118,54 +119,3 @@ class UserInfoView(APIView):
return Response(res.dict) return Response(res.dict)
def post(self, request):
res = BaseResponse()
# 获取多个file
files = request.FILES.getlist('file', None)
for file_obj in files:
# 将文件缓存到本地后上传
try:
app_type = file_obj.name.split(".")[-1]
if app_type in ['png','jpeg','jpg']:
#上传图片
pass
else:
raise
except Exception as e:
res.code = 1003
res.msg = "错误的类型"
return Response(res.dict)
# img_file_name = request.user.head_img
# if img_file_name == "" or img_file_name == '/files/imgs/head_img.jpeg':
old_head_img = request.user.head_img
random_file_name = make_from_user_uuid(request.user)
head_img = "/".join([settings.MEDIA_URL.strip("/"), "imgs", random_file_name + "." + app_type])
local_file = os.path.join(settings.MEDIA_ROOT,"imgs",random_file_name + "." + app_type)
# 读取传入的文件
try:
destination = open(local_file, 'wb+')
for chunk in file_obj.chunks():
# 写入本地文件
destination.write(chunk)
destination.close()
except Exception as e:
res.code = 1003
res.msg = "数据写入失败"
return Response(res.dict)
try:
request.user.head_img = head_img
request.user.save()
if old_head_img != "" or old_head_img != '/files/imgs/head_img.jpeg':
storage = Storage(request.user)
storage.delete_file(os.path.basename(old_head_img))
except Exception as e:
res.code = 1003
res.msg = "头像保存失败"
return Response(res.dict)
return Response(res.dict)

@ -3,43 +3,23 @@
# project: 3月 # project: 3月
# author: liuyu # author: liuyu
# date: 2020/3/6 # date: 2020/3/6
from api.utils.app.apputils import get_random_short,SaveAppInfos
from api.utils.storage.storage import Storage
from api.models import Apps,AppReleaseInfo
from api.utils.app.randomstrings import make_app_uuid
from rest_framework.views import APIView from rest_framework.views import APIView
from api.utils.response import BaseResponse from api.utils.response import BaseResponse
from api.utils.auth import ExpiringTokenAuthentication from api.utils.auth import ExpiringTokenAuthentication
from api.utils.app.randomstrings import make_from_user_uuid from api.utils.app.randomstrings import make_from_user_uuid
from rest_framework.response import Response from rest_framework.response import Response
from api.utils.app.apputils import get_random_short,SaveAppInfos from fir_ser import settings
from api.utils.storage.storage import Storage from api.utils.TokenManager import DownloadToken
from api.models import Apps import os,json
from api.utils.app.randomstrings import make_app_uuid
class AppAnalyseView(APIView):
class OssUploadView(APIView):
authentication_classes = [ExpiringTokenAuthentication, ] authentication_classes = [ExpiringTokenAuthentication, ]
#
# def get(self,request):
# res = BaseResponse()
# upload_key = request.query_params.get("upload_key", None)
# app_id = request.query_params.get("app_id", None)
# if upload_key:
# if app_id:
# #修改app图片
# app_obj = Apps.objects.filter(app_id=app_id).first()
# if app_obj:
# release_obj = AppReleaseInfo.objects.filter(app_id=app_obj,is_master=True).first()
#
# else:
# res.code = 1005
# res.msg = '该应用找不到'
# pass
# else:
# res.code = 1004
#
#
# return Response(res.dict)
#
def post(self, request): def post(self, request):
res = BaseResponse() res = BaseResponse()
@ -108,3 +88,167 @@ class OssUploadView(APIView):
res.code = 10003 res.code = 10003
return Response(res.dict) return Response(res.dict)
class UploadView(APIView):
'''
上传文件接口
'''
authentication_classes = [ExpiringTokenAuthentication, ]
def get(self,request):
res = BaseResponse()
storage = Storage(request.user)
request_upload_key=request.query_params.get("upload_key",None)
app_id=request.query_params.get("app_id",None)
ftype = request.query_params.get("ftype",None)
if ftype and app_id and request_upload_key :
if ftype =='app':
app_obj = Apps.objects.filter(app_id=app_id, user_id=request.user).first()
elif ftype and ftype == 'head':
if request.user.uid != app_id:
res.code = 1007
res.msg = '该用户不存在'
return Response(res.dict)
else:
app_obj=True
else:
app_obj=False
if app_obj:
app_type = request_upload_key.split(".")[-1]
if app_type not in ["apk", "ipa", 'png', 'jpeg', 'jpg']:
res.code = 1006
res.msg='类型不允许'
else:
upload_key = make_from_user_uuid(request.user)+'.'+app_type
upload_token = storage.get_upload_token(upload_key)
storage_type = request.user.storage.storage_type
res.data = {"domain_name": request.user.domain_name,
"upload_token": upload_token,
"upload_key": upload_key,
"storage": storage_type,
"app_id":app_id,
"ftype":ftype}
else:
res.code = 1006
res.msg = '该应用不存在'
else:
res.code = 1006
return Response(res.dict)
def post(self, request):
res = BaseResponse()
# 获取多个file
files = request.FILES.getlist('file', None)
certinfo = request.data.get('certinfo', None)
try:
certinfo = json.loads(certinfo)
if not certinfo:
res.msg = "token 校验失败"
res.code = 1006
return Response(res.dict)
except Exception as e:
print(e)
res.msg = "token 校验失败"
res.code = 1006
return Response(res.dict)
token_obj = DownloadToken()
if token_obj.verify_token(token=certinfo.get("upload_token",None),release_id=certinfo.get("upload_key",None)):
app_id = certinfo.get("app_id", None)
ftype = certinfo.get("ftype",None)
if ftype and ftype == 'app':
app_obj = Apps.objects.filter(app_id=app_id, user_id=request.user).first()
if not app_obj:
res.code = 1006
res.msg = '该应用不存在'
return Response(res.dict)
elif ftype and ftype == 'head':
if request.user.uid != app_id:
res.code = 1007
res.msg = '该用户不存在'
return Response(res.dict)
else:
res.code = 1008
res.msg = '该请求不存在'
return Response(res.dict)
if not files:
res.msg="文件不存在"
for file_obj in files:
try:
app_type = file_obj.name.split(".")[-1]
if app_type not in ["apk","ipa",'png','jpeg','jpg']:
raise TypeError
except Exception as e:
print(e)
res.code = 1003
res.msg = "错误的类型"
return Response(res.dict)
random_file_name = make_from_user_uuid(request.user)
local_file = os.path.join(settings.MEDIA_ROOT,certinfo.get("upload_key",random_file_name))
# 读取传入的文件
try:
destination = open(local_file, 'wb+')
for chunk in file_obj.chunks():
destination.write(chunk)
destination.close()
except Exception as e:
res.code = 1003
res.msg = "数据写入失败"
try:
os.remove(local_file)
except Exception as e:
print(e)
return Response(res.dict)
else:
res.msg = "token 校验失败"
res.code = 1006
return Response(res.dict)
def put(self,request):
res = BaseResponse()
certinfo = request.data.get('certinfo',None)
if certinfo:
app_id = certinfo.get("app_id", None)
ftype = certinfo.get('ftype',None)
storage = Storage(request.user)
if ftype and ftype == 'app':
app_obj = Apps.objects.filter(app_id=app_id, user_id=request.user).first()
if app_obj:
release_obj = AppReleaseInfo.objects.filter(app_id=app_obj,is_master=True).first()
if release_obj:
old_file_key = release_obj.icon_url
release_obj.icon_url = certinfo.get("upload_key")
release_obj.save()
storage.delete_file(old_file_key)
return Response(res.dict)
elif ftype and ftype == 'head':
if request.user.uid != app_id:
res.code = 1007
res.msg = '该用户不存在'
return Response(res.dict)
old_file_key = request.user.head_img
request.user.head_img = certinfo.get("upload_key")
request.user.save()
if old_file_key != "" or old_file_key != 'head_img.jpeg':
storage.delete_file(old_file_key)
return Response(res.dict)
else:
pass
res.code = 1008
return Response(res.dict)

Loading…
Cancel
Save