i have blueprint like below, and using flask-upload for uploading file
#blueprint.route('/', methods=['GET', 'POST'])
def upload_file1():
# user = User.query.filter_by(id=current_user.id).first_or_404()
form = PhotoFormUpload()
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
foto = form.photo_upload.data.lower()
filename = user_photos.save(foto)
update_avatar = User.query.filter_by(id=current_user.id).update(dict(avatar=filename))
db.session.commit()
flash('Upload Success', category='success')
return render_template('upload/display_photo.html', filename=filename)
else:
return render_template('upload/upload.html', form=form)
i change
foto = form.photo_upload.data
to
foto = form.photo_upload.data.lower()
but it doesnt works
how do i rename uploaded file name?
Answer on your question exist in http://pythonhosted.org/Flask-Uploads/
save(storage, folder=None, name=None)
Parameters:
storage – The uploaded file to save.
folder – The subfolder within the upload set to save to.
name – The name to save the file as. If it ends with a dot, the file’s extension will be appended to the end.
Example: user_photos.save(pathToDirectory, name=NewName)
I used the following method to rename the uploaded file on the fly
file = request.files['file']
file.filename = "abc.txt" #some custom file name that you want
file.save("Uploads/"+file.filename)
Related
I want to extract the tif file from a range of URL. This code works for one zip file, but if I want to extract zips in a range(1,43) it doesn't work
the error is:
BadZipFile: File is not a zip file
Could somebody help me?
print('Downloading started')
for number in range(1,3):
url = f'https://downloadagiv.blob.core.windows.net/dhm-vlaanderen-ii-dsm-raster-1m/DHMVIIDSMRAS1m_k{number}.zip'
req = requests.get(url)
# Split URL to get the file name
filename = url.split('/')[-1]
req = requests.get(url)
print('Downloading Completed')
zipfile= ZipFile(BytesIO(req.content))
listOfFileNames = zipfile.namelist()
for filename in listOfFileNames:
# Check filename endswith tif
if filename.endswith('.tif'):
# Extract a single file from zip
zipfile.extract(filename, '/content/gdrive/My Drive')
I am uploading a file using Spring MultipartFile. I need to store the uploaded file attributes like creation date and modified date. Currently I am using following approach:
File dest = new File(uploadfile.getOriginalFilename());
dest.createNewFile();
FileOutputStream fos = new FileOutputStream(dest);
fos.write(uploadfile.getBytes());
fos.close();
Path filee = dest.toPath();
BasicFileAttributes attr = Files.readAttributes(filee, BasicFileAttributes.class);
System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());
where uploadfile is the object of spring boot MultipartFile.
Referred links :
How to convert a multipart file to File?
Get java.nio.file.Path object from java.io.File
Determine file creation date in Java
The issue is that I am getting creation date and modified date as the current date only and probably the reason is that the new file object is resetting these values. How can I get the attributes of the original uploaded file?
The file meta data (like your creationTime, lastAccessTime, lastModifiedTime) is not part of the file, but the filesystem. Thus by uploading a file you only get the file and not the additional (meta) data that is managed by the filesystem.
You could add the last modified date to the upload form with the help of the File API (access and creation are not supported), but these can be manipulated by the user and thus you cannot trust them, if that is not a problem for you here an example from: https://developer.mozilla.org/en-US/docs/Web/API/File/lastModified
html:
<!-- inside your form -->
<input type="file" multiple id="fileInput">
javascript:
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(event) {
// files is a FileList object (similar to NodeList)
const files = event.target.files;
for (let i = 0; i < files.length; i++) {
const date = new Date(files[i].lastModified);
alert(files[i].name + ' has a last modified date of ' + date);
// TODO add the date as a hidden input to your form
}
});
I'm uploading a file that is a zip in a web app and passing it as type "Part" and I need to grab the name of the file that I originally uploaded. I can't seem to figure out for the life of me how to grab the actual name of the uploaded file. I've tried the following assuming my Part is uploaded with the original file name as "ABCD". My Part object will be named "file":
file.getHeaderNames() yields "content-type" and "content-disposition"
file.getName() yields "BPzip8237267963573706108tmp" which is the temp file's name
Any ideas on how I would go about doing this?
// define variable for file name
String filename = "";
// get part
Part file = request.getPart("file");
// get filename from part header
for (String s: file.getHeader("content-disposition").split(";")) {
if (s.trim().startsWith("filename")) {
filename = s.split("=")[1].replace("\"", "");
break;
}
}
I have successfully uploaded a file to blobstore using this code.
But I am unable to download it.
What I am doing is:
`class PartnerFileDownloadHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, blob_key):
resource = str(urllib.unquote(blob_key))
logging.info('I am here.') //This gets printed successfully.
blob_info = blobstore.BlobInfo.get(blob_key)
logging.info(blob_info) //This gets logged too.
self.send_blob(blob_info)`
I have also tried:
blobstore.BlobReader(blob_key).read()
and I get file data in string form but I can not write it to file, as local file system can not be accessed from within a handler, I guess.
The way I am uploading a file is the only way in my project so I can not use the usual way specified in the Google's official tutorial. Also The file I am uploading to blobstore is not present at my local file syatem, I pick it from a URL, perhaps this is the problem why I am not able to download the file.
Any suggestions?
Thanks
Perhaps you should use resource instead of blob_key from your code sample?
class PartnerFileDownloadHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, blob_key):
resource = str(urllib.unquote(blob_key))
self.send_blob(resource)
you can use DownloadHandler as this:
from mimetypes import guess_type
def mime_type(filename):
return guess_type(filename)[0]
class Thumbnailer(blobstore_handlers.BlobstoreDownloadHandler):
def get(self , blob_key):
if blob_key:
blob_info = blobstore.get(blob_key)
if blob_info:
save_as1 = blob_info.filename
mime_type=mime_type(blob_info.filename)
self.send_blob(blob_info,content_type=mime_type,save_as=save_as1)
Here is my code to accept files uploaded by users:
def post(self):
logging.info('(POST) Uploading new file')
# saving file in the database
file = Files()
file.file = db.Blob(self.request.body)
file.put()
How can I avoid upload of files larger than 100Kb and which file type is not .torrent? (I believe I should verify the file's mime type?)
You can't prevent the file from being uploaded - by the time your request handler is executed, the file has already been uploaded. All you can do is discard the file and return an error message.
Since it appears the file is being uploaded as the body of the request, rather than from an HTML form, you can determine the content type by getting self.request.headers["Content-Type"], and the size with len(self.request.body).