def uploadimage(roll_no): file = request.files["File"] filepath = os.path.realpath(file.filename) file_extenstion = file.filename.rsplit(".", 1)[1].lower() if file and file_extenstion in ['jpg', 'jpeg', 'png']: filename = secure_filename(file.filename) else: return "Invalid File Format" drive = auth.getCredentials() gfolder = "https://drive.google.com/drive/u/4/folders/1x0oNCpM1DWHSGmWrAm1LWI05Xws43Wzy?usp=sharing" gfolder_id = "1x0oNCpM1DWHSGmWrAm1LWI05Xws43Wzy" # Call the Drive v3 API UPLOAD_FOLDER = "uploadfiles\\studentimages\\" app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER file.save(os.path.join(app.config["UPLOAD_FOLDER"], str(roll_no) + ".jpg")) file1 = drive.CreateFile({ "title": str(roll_no) + ".jpg", "mimeType": "image/jpg", "parents": [{ "kind": gfolder, "id": gfolder_id }], }) # Create GoogleDriveFile instance with title 'Hello.txt'. # Set content of the file from given string. file1.SetContentFile(UPLOAD_FOLDER + str(roll_no) + ".jpg") file1.Upload() file_id = file1.get("id") return file_id
def uploadInternships(email): file = request.files["File"] file_name = request.form.get("file_name") file_type = request.form.get("file_type") filepath = os.path.realpath(file.filename) file_extenstion = file.filename.rsplit(".", 1)[1].lower() if file and file_extenstion in ['pdf']: filename = secure_filename(file.filename) else: return "Invalid File Format" #roll_no = int(request.form["roll_no"]) # Call the Drive v3 API drive = auth.getCredentials() gfolder = "https://drive.google.com/drive/u/4/folders/1x0oNCpM1DWHSGmWrAm1LWI05Xws43Wzy?usp=sharing" gfolder_id = "1x0oNCpM1DWHSGmWrAm1LWI05Xws43Wzy" UPLOAD_FOLDER = "uploadfiles\\" app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename)) file1 = drive.CreateFile({ "title": filename, "mimeType": "application/pdf", "parents": [{ "kind": gfolder, "id": gfolder_id }], }) file1.SetContentFile(UPLOAD_FOLDER + filename) file1.Upload() file_id = file1.get("id") student_data = mongo.db.studentdetails.find_one({"email": email}, { "roll_no": 1, "name": 1, "branch": 1, "current_year": 1 }) mongo.db.student_activity.insert_one({ "roll_no": int(student_data['roll_no']), "name": student_data['name'], "branch": student_data['branch'], "current_year": student_data['current_year'], "file_name": file_name, "file_type": file_type, "file_id": file_id }) return "file Upload successful"
def storeDetails(): if request.method == 'POST': file = request.files['file-name'] if file.filename == " ": flash("pls select a file") return redirect('upload') else: courseTitle = request.form['course-title'] courseCode = valid_code(request.form['course-code']) Category = request.form['category'] if (courseTitle and courseCode and Category and valid_ext(file.filename) and 'file-name' in request.files): # first upload file to base folder fileName = secure_filename(file.filename) file.save(os.path.join(bucket, fileName)) filePath = os.path.join(bucket, fileName) # second push file to cloud download_id = upload_file(filePath) # store file details in data base # past question will have the year beside it - past question-2019 newDetail = courseDetails( filepath = filePath, filename = fileName, coursetitle = courseTitle, coursecode = courseCode, download_id = download_id, category = Category, ) session.rollback() session.add(newDetail) session.commit() # rename file with course title field filename = secure_filename(file.filename) fileExt = "."+filename.rsplit('.',1)[1].lower() #rename file in database getFile = session.query(courseDetails).filter_by(filename=fileName).one() file_num = str(getFile.id) newName = getFile.coursetitle+" uid: "+file_num getFile.filename = newName+fileExt # getFile.coursetitle = newName session.add(getFile) session.commit() return redirect(url_for('recent')) else: msg = Markup("Make sure you put in ALL file details before uploading.<br/>Files must be in DOC or PDF format") flash(msg) return redirect('upload') else: return redirect('upload')
def gdrive_upload(file, name, typpe, allowed_func, curr_folder, modelClass, resource): file_rename = "" msg = "not ok" if file and allowed_func(file.filename): filename = secure_filename(file.filename) curr_path = curr_folder + '/' + str(current_user.id) if os.path.isdir(curr_path) == False: os.makedirs(curr_path) file.save(os.path.join(curr_path, filename)) uploading = upload_((curr_path + '/' + filename, None)) lc = Type.query.filter_by(name=str(typpe)).first() if uploading: if resource == 'profile': proft = Profile.query.filter( and_(Profile.userid == current_user.id, Profile.typeID == lc.id)).all() for p in proft: p.status = 0 db.session.add(p) db.session.commit() instance_ = modelClass(link=str(uploading), userid=current_user.id, typeID=lc.id) db.session.add(instance_) db.session.commit() else: instance_ = modelClass(link=str(uploading), userid=current_user.id, name=name, typeID=lc.id) db.session.add(instance_) db.session.commit() msg = "ok" shutil.rmtree(curr_path) return uploading, msg return None, msg
def uploadfile(): file = request.files["File"] file_name = request.form.get("file_name") file_type = request.form.get("file_type") filepath = os.path.realpath(file.filename) file_extenstion = file.filename.rsplit(".", 1)[1].lower() if file and file_extenstion in ALLOWED_EXTENSIONS: filename = secure_filename(file.filename) else: return "Invalid File Format" drive = auth.getCredentials() gfolder = "https://drive.google.com/drive/folders/16JMHYtZq-qAZJTuXl5bRtW84uTFNsLwC?usp=sharing" gfolder_id = "16JMHYtZq-qAZJTuXl5bRtW84uTFNsLwC" roll_no = int(request.form["roll_no"]) # Call the Drive v3 API UPLOAD_FOLDER = "uploadfiles\\" app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename)) file1 = drive.CreateFile({ "title": filename, "mimeType": "application/pdf", "parents": [{ "kind": gfolder, "id": gfolder_id }], }) # Create GoogleDriveFile instance with title 'Hello.txt'. # Set content of the file from given string. file1.SetContentFile(UPLOAD_FOLDER + filename) file1.Upload() file_id = file1.get("id") student_exist = mongo.db.studentdetails.count_documents( {"roll_no": roll_no}) if student_exist != 0: mongo.db.studentdetails.update( {"roll_no": roll_no}, { "$push": { "documents": { "file_name": file_name, "file_id": file_id, "document_type": file_type } } }, ) data = mongo.db.studentdetails.find({"roll_no": roll_no}, { "_id": 0, "internships": 1 }) if file_type == "internship": for document in data: internship_count = document["internships"] if internship_count == '-': internship_count = 0 internship_count = int(internship_count) + 1 mongo.db.studentdetails.update( {"roll_no": roll_no}, {"$set": { "internships": internship_count }}) else: data = mongo.db.studentdetails.find( {"roll_no": roll_no}, {"documents.document_type": "other"}) count = 0 for document in data: for file_type in document["documents"]: if file_type["document_type"] == "other": count = count + 1 mongo.db.studentdetails.update( {"roll_no": roll_no}, {"$set": { "extracurricular_activities": count }}) return "file Upload successful" else: return "student not found"
def uploads(): if request.method == 'POST': if 'msg[Reply_to]' in request.form: Reply_to = request.form['msg[Reply_to]'] else: return json.dumps( {"error": "Failed! Missing parameter 'msg[Reply_to]'"}) # if 'msg[To]' in request.form: # To = request.form['msg[To]'] # else: # return json.dumps({"error": "Failed! Missing parameter 'msg[To]'"}) if 'subject' in request.form: subject = request.form['subject'] else: return json.dumps({"error": "Failed! Missing parameter 'subject'"}) if 'address' in request.form: address = request.form['address'] else: return json.dumps({"error": "Failed! Missing parameter 'address'"}) if 'price' in request.form: price = request.form['price'] else: return json.dumps({"error": "Failed! Missing parameter 'price'"}) if 'name' in request.form: name = request.form['name'] else: return json.dumps({"error": "Failed! Missing parameter 'name'"}) prefix = path + "/uploads/" + str(int(round(time.time() * 1000))) if not os.path.exists(prefix): os.makedirs(prefix) if 'template' not in request.files: return json.dumps({"error": "No template found!"}) else: uploadfile = request.files.getlist("template") for file in uploadfile: templateName = os.path.join(prefix + "/", secure_filename(file.filename)) file.save(templateName) uploadFileNames = [] if 'attachFiles' not in request.files: print('no file') else: uploadsFiles = request.files.getlist("attachFiles") for file in uploadsFiles: fileName = os.path.join(prefix + "/", secure_filename(file.filename)) uploadFileNames.append(fileName) file.save(fileName) values = {} temp = EmailTemplate(template_name=templateName, values=values) server = MailServer(server_name='smtp.office365.com', username='******', password='******', port=587, require_starttls=True) msg = MailMessage(from_email='*****@*****.**', to_emails=[Reply_to], subject=subject, template=temp, attachments=uploadFileNames) send(mail_msg=msg, mail_server=server) ## delete downloaded files os.remove(templateName) for name in uploadFileNames: if (os.path.exists(name)): os.remove(name) os.rmdir(prefix) return json.dumps({"success": "sent email to " + Reply_to})
def sendEmail(): if request.method == 'POST': ############## Get params from request ############### ## reply_to : destination email ## file_id : email file id of google drive %% You can get file id using this end point "ec2-18-216-179-182.us-east-2.compute.amazonaws.com/fileList" ## subject : Subject of Email ## attachment : attach file params ## address : Address information ## price : Price param ## name : Name param ####################################################### if 'msg[Reply_to]' in request.form: Reply_to = request.form['msg[Reply_to]'] else: return json.dumps( {"error": "Failed! Missing parameter 'msg[Reply_to]'"}) if 'msg[To]' in request.form: To = request.form['msg[To]'] else: return json.dumps({"error": "Failed! Missing parameter 'msg[To]'"}) templateID_folder = "" if 'templateID_folder' in request.form: templateID_folder = request.form['templateID_folder'] elif 'attachFiles' not in request.files: return json.dumps( {"error": "Failed! Missing parameter 'templateID_folder'"}) if 'address' in request.form: address = request.form['address'] else: return json.dumps({"error": "Failed! Missing parameter 'address'"}) if 'price' in request.form: price = request.form['price'] else: return json.dumps({"error": "Failed! Missing parameter 'price'"}) if 'name' in request.form: name = request.form['name'] else: return json.dumps({"error": "Failed! Missing parameter 'name'"}) templateID = "" if 'templateID' in request.form: templateID = request.form['templateID'] elif 'template' not in request.files: return json.dumps({"error": "No template found!"}) if 'subject' in request.form: subject = request.form['subject'] else: return json.dumps({"error": "Failed! Missing parameter 'subject'"}) prefix = path + "/uploads/" + str(int(round(time.time() * 1000))) if not os.path.exists(prefix): os.makedirs(prefix) os.makedirs(prefix + "/attachments") if 'template' in request.files: uploadfile = request.files.getlist("template") for file in uploadfile: templateFileName = os.path.join(prefix + "/", secure_filename(file.filename)) file.save(templateFileName) attachFileNames = [] if 'attachFiles' in request.files: uploadsFiles = request.files.getlist("attachFiles") for file in uploadsFiles: fileName = os.path.join(prefix + "/", secure_filename(file.filename)) attachFileNames.append(fileName) file.save(fileName) ## get instance of connection for google drive service = getConnection() if templateID != "": templateFileName = prefix + "/email.html" ## download file which id is file_id and save as "email.html" req = service.files().get_media(fileId=templateID) fh = io.FileIO(templateFileName, 'w') downloader = MediaIoBaseDownload(fh, req) done = False try: while done is False: status, done = downloader.next_chunk() except Exception as inst: return json.dumps({ "error": "Failed in downloading html file. please check fileId again" }) fh.close() ### download attached files # templateID_folder = "1Tnw9ShNslKIwt7awqxQQ7Awva7rMXE3T" if templateID_folder != "": fileIds = get_files_in_folder(service, templateID_folder) attachFileNames = download(service, fileIds, prefix + "/attachments") ## Define values which are needed to exchange with email text. values = {} # values['username'] = '******' # values['from'] = '*****@*****.**' # values['url'] = '' ## Sending email to reply_to temp = EmailTemplate(template_name=templateFileName, values=values) server = MailServer(server_name='smtp.office365.com', username='******', password='******', port=587, require_starttls=True) msg = MailMessage(from_email='*****@*****.**', to_emails=[Reply_to], subject=subject, template=temp, attachments=attachFileNames) send(mail_msg=msg, mail_server=server) ## delete downloaded files os.remove(templateFileName) for name in attachFileNames: if (os.path.exists(name)): os.remove(name) os.rmdir(prefix + "/attachments") os.rmdir(prefix) return json.dumps({"success": "sent email to " + Reply_to})