madprabh's avatar

Checking if file being uploaded is unique

Hey Folks,

I am building a feature which allos the users to upload files through Trix editor. So people could paste snapshots as well as drag and drop files into the editor. I then process this and upload it on S3 bucket.

Can someone let me know how I can check that the file (not just the name but content) is unique before I upload it to S3

My client side code is this

document.addEventListener("trix-attachment-add", function(event){
		        	var attachment = event.attachment;
		        	console.log(attachment.file)
		        	if (attachment.file)
		        	{
		        		var file=attachment.file;
					       
					       let formData = new FormData();
					       formData.append("attachments", file);
					       		axios.post('/fileuploads', formData, {
			                    headers: {
			      					'Content-Type': 'multipart/form-data'
			    				}
			                })
			                .then(response=>{
			                    this.response_message=response;
			                    
			                    attachment.setAttributes({
			                    	url: this.response_message['data']['data'],
			                    	href: this.response_message['data']['data']
			                    });
			                    
			                }, (error) => {
			                    
			                   
			                })
		        	}
		        }); // Listen to the changes on the 

And server side is this

Route::post('/fileuploads', function() {
		$fileUploadResponse=request()->file('attachments')->store('problems/'.\Auth::id(),'s3');
		$url = Storage::url($fileUploadResponse);
		return response()->json(['isvalid'=>true,'data'=>$url ,'message'=>'File uploaded successfully.']);
	});

I am ok to do that validation either on client or server. I don't have a preference. Any help is very appreciated.

0 likes
5 replies
MichalOravec's avatar

FIx you github account on Laracasts profile. Use only username and not full url.

Snapey's avatar

create an md5 hash of the file contents and compare it

madprabh's avatar

Thanks @snapey And what would you suggest, should I do it on the client or the server?

If its the client are you suggesting something like

CryptoJS.MD5(attachment.file);

And I am not sure yet how to do that on the server, I will try to figure it out. What I want to be able to do is before uploading the data to AWS S3, I want to check the md5 and ignore the upload if the file is already uploaded previously.

martinbean's avatar

Store the MD5 hash of a file’s contents along with the file in your database. Then when a user uploads a file, you hash it and check it against your database of existing hashes. If you find a match, display an alter to the user saying they’ve already uploaded that file or whatever.

Please or to participate in this conversation.