This is a migrated thread and some comments may be shown as answers.

upload saveurl and custom function

4 Answers 1246 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
SOYEON
Top achievements
Rank 1
SOYEON asked on 27 Jan 2021, 02:05 PM

i use Springboot for backend and database, front as react.

 

i want to use saveUrl in kendo-upload ui post my image to springboot and saving image in mysql db.

 

i have "uploadFile" variable as axios request parameter

 

 

@RestController
@CrossOrigin
public class MemberController {

@Autowired
MemberMapper mapper;


MultipartFile upload;
String photoname;

 

 

@PostMapping(value = "/member/upload", consumes = {"multipart/form-data"})
public Map<String, String> fileUpload(@RequestParam MultipartFile uploadFile, HttpServletRequest request){
String uploadPath = request.getSession().getServletContext().getRealPath("/WEB-INF/photo");
System.out.println(uploadPath);


int pos = uploadFile.getOriginalFilename().lastIndexOf("."); 
String ext = uploadFile.getOriginalFilename().substring(pos);


Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
photoname = "jeju" + sdf.format(date) + ext;

upload = uploadFile;

Map<String, String> map = new HashMap<String, String>();
map.put("photoname", photoname);
return map;
}

 

 

 

and 

for react

 

let uploadFile = null;

    imageUpload=(e)=>{
        const uploadFile = e.affectedFiles[0].name;
        
        const memberFile = new FormData();
        memberFile.append("uploadFile",uploadFile);
        axios({
            method: 'post',
            url: URL + '/member/upload',
            data: memberFile,
            headers: {'Content-Type':'multipart/form-data'}
        }).then(response=>{
            alert(response.data.photoname+" ==> save as this name");
            
            this.setState({
                photoname: response.data.photoname
            })
        }).catch(err=>{
            console.log("error while uploading images:"+err);
        })
    }

 

 

 onAdd = (event) => {
        const afterStateChange = () => {
            event.affectedFiles
                .filter(file => !file.validationErrors)
                .forEach(file => {
                    const reader = new FileReader();
                    reader.onloadend = (ev) => {
                        this.setState({
                            filePreviews: {
                                ...this.state.filePreviews,
                                [file.uid]: ev.target.result
                            }
                        });
                    };
                    reader.readAsDataURL(file.getRawFile());
                });
        };
        this.setState({
            files: event.newState,
            events: [
                ...this.state.events,
                `selected file: ${event.affectedFiles[0].name}`
            ],
        }, afterStateChange);
        uploadFile = event.affectedFiles[0].name;
    }

 

 

 

render(){

    return (

 <div>
                    <InputLabel id="demo-simple-select-label">picture</InputLabel>
                    <br />
                    <Upload 
                        batch={false}
                        multiple={true}
                        files={this.state.files}
                        onAdd={this.onAdd}
                        onRemove={this.onRemove}
                        onProgress={this.onProgress}
                        onStatusChange={this.onSatusChange}
                        withCredentials={false}
                        saveUrl={URL + '/member/upload'}
                        removeUrl={'https://demos.telerik.com/kendo-ui/service-v4/upload/remove'}
                        onChange={this.imageUpload.bind(this)}
                    />
                    <div className={'example-config'} style={{ marginTop: 20 }}>
                        <ul className={'event-log'}>
                            {
                                this.state.events.map(event => <li key={event}>{event}</li>)
                            }
                        </ul>
                    </div>
                    {
                        this.state.files.length ? 
                        <div className={'img-preview example-config'}>
                            <h3>image preview</h3>
                            {
                                Object.keys(this.state.filePreviews)
                                    .map((fileKey, index) => (<img 
                                        src={this.state.filePreviews[fileKey]} 
                                        alt={index}
                                        style={{ width: 200, margin: 10 }} 
                                    />))
                            }
                        </div> : undefined
                    }
                </div>

);

 

}

4 Answers, 1 is accepted

Sort by
0
Stefan
Telerik team
answered on 28 Jan 2021, 10:58 AM

Hello,

Thank you for the details.

The saveUrl can be used as a string URL to the API and the Upload will automatically make a request using axios.

The other option is the use the saveURL as a function and make the request programmatically:

https://github.com/telerik/kendo-react/issues/193

Could you please share the issue you are facing with the Upload the saveUrl prop?

Regards,
Stefan
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

0
SOYEON
Top achievements
Rank 1
answered on 29 Jan 2021, 01:17 AM


 

 

@RestController
@CrossOrigin
public class MemberController {

@Autowired
MemberMapper mapper;


MultipartFile upload;
String photoname;

 

 

@PostMapping(value = "/member/upload", consumes = {"multipart/form-data"})
public Map<String, String> fileUpload(@RequestParam MultipartFile uploadFile, HttpServletRequest request){
String uploadPath = request.getSession().getServletContext().getRealPath("/WEB-INF/photo");
System.out.println(uploadPath);


int pos = uploadFile.getOriginalFilename().lastIndexOf("."); 
String ext = uploadFile.getOriginalFilename().substring(pos);


Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
photoname = "jeju" + sdf.format(date) + ext;

upload = uploadFile;

Map<String, String> map = new HashMap<String, String>();
map.put("photoname", photoname);
return map;
}

 

 

 

and 

for react

const fileStatuses = [
    'UploadFailed',
    'Initial',
    'Selected',
    'Uploading',
    'Uploaded',
    'RemoveFailed',
    'Removing'
];




let uploadFile = null;

class SignupPageComp extends Component {


    constructor(props) {
        super(props);

        console.log("SignupPageComp constructor", props);
        
        this.state={
            id:'',  
            pass:'',
            pwCheck: "",
            name : '',
            gender: '',
            photo: null,
            photoname: '',
            address : '',
            addrdetail: '',
            email : '',
            hp : "",
            idcanUse: false,
            files: [],
            events: [],
            filePreviews: {},
        };

    
        this.onIdChk=this.onIdChk.bind(this);
    }

    
    changeEvent=(e)=>{
        
        console.log(e.target.id+":"+e.target.value);
    
        this.setState({
            [e.target.name]:e.target.value
        })
    }


    onIdChk=(e)=>{
        e.preventDefault();
        console.log(this.state.id);
        const data = {
            id: this.state.id
        }
       
        let url = URL + '/member/checkid?id=' + this.state.id;
        axios.get(url)
        .then(response=>{

            if(response.data.idcanUse === "true")
            {
                alert("id okay");
                this.setState({
                    idcanUse: true
                })
            }
            else if(response.data.idcanUse === "false")
            {
                alert("id already exists");
                this.setState({
                    id: '',
                })
            }
        }).catch(err => {
            console.log("id checking error:"+err);
        })
    }

    onSubmitHandler = (e) => {
        e.preventDefault();
        this.onInsertMember();
    };

    
    imageUpload=(e)=>{
        const uploadFile = e.target.files[0];

       
        const memberFile = new FormData();
        memberFile.append("uploadFile",uploadFile);

        axios({
            method: 'post',
            url: URL + '/member/upload',
            data: memberFile,
            headers: {'Content-Type':'multipart/form-data'}
        }).then(response=>{
            alert(response.data.photoname+" => save as this name");

            this.setState({
                photoname: response.data.photoname
            })
        }).catch(err=>{
            console.log("photo upload error:"+err);
        })
    }

    

    onInsertMember = () => {
        let data = this.state;
        let url = URL + "/member/insert";

        axios.post(url, data)
        .then(response => {
           
            this.setState({
                id:'',  
                pass:'',
                pwCheck: "",
                name : '',
                gender: '',
                photo: null,
                photoname: '',
                address : '',
                addrdetail: '',
                email : '',
                hp : "",
                idcanUse: false,
            })

            
            this.props.history.push("/login");
        }).catch(err=>{
            console.log("Sign up error:"+err);
        })
    }

    handleChange = (event) => {
        this.setState({
            gender: event.target.value,
        });
    };

    onAdd = (event) => {
        const afterStateChange = () => {
            event.affectedFiles
                .filter(file => !file.validationErrors)
                .forEach(file => {
                    const reader = new FileReader();

                    reader.onloadend = (ev) => {
                        this.setState({
                            filePreviews: {
                                ...this.state.filePreviews,
                                [file.uid]: ev.target.result
                            }
                        });
                    };

                    reader.readAsDataURL(file.getRawFile());
                });
        };

        this.setState({
            files: event.newState,
            events: [
                ...this.state.events,
                `selected file: ${event.affectedFiles[0].name}`
            ],
        }, afterStateChange);

        uploadFile = event.affectedFiles[0].name;
    }

    onRemove = (event) => {
        const filePreviews = {
            ...this.state.filePreviews
        };

        event.affectedFiles.forEach(file => {
            delete filePreviews[file.uid];
        });

        this.setState({
            files: event.newState,
            events: [
                ...this.state.events,
                `file removed: ${event.affectedFiles[0].name}`
            ],
            filePreviews: filePreviews
        });
    }

    onProgress = (event) => {
        this.setState({
            files: event.newState,
            events: [
                ...this.state.events,
                `on progress: ${event.affectedFiles[0].progress} %`
            ]
        });
    }

    onStatusChange = (event) => {
        const file = event.affectedFiles[0];

        this.setState({
            files: event.newState,
            events: [
                ...this.state.events,
                `File '${file.name}' status changed to: ${fileStatuses[file.status]}`
            ]
        });
    }
    
    render() {
        const { classes } = this.props;
        console.log("SingupPageComp render()", this.props);
        return (
            <div>
                <form
                className={classes.root}
                noValidate autoComplete="off"
                onSubmit = { this.onSubmitHandler.bind(this) }
                >
                <h1>Sing Up</h1>
                <div>
                    <h4 className="showIdResult">{this.state.showIdResult}</h4>
                </div>
                <br />
                <TextField id="standard-secondary" label="email" color="secondary" 
                type="email" name="email" value={ this.state.email }
                onChange = { this.changeEvent.bind(this) } />
                
                
                <br />
                
                
                
                <TextField id="standard-secondary" label="name" color="secondary" 
                type="text" name="name" value={ this.state.name }
                onChange = { this.changeEvent.bind(this) } />

                <br />
                
                <TextField id="standard-secondary" label="id" color="secondary" 
                type="text" name="id" value={ this.state.id }
                onChange = { this.changeEvent.bind(this) } />

                <button type="button"
                onClick={this.onIdChk.bind(this)}>
                    Id Check
                </button>
                <br />
                
                <TextField id="standard-secondary" label="pass" color="secondary" 
                type="password" name="pass" value={ this.state.pass }
                onChange = { this.changeEvent.bind(this) } />

                <br />
                
                <TextField id="standard-secondary" label="passwordcheck" color="secondary" 
                type="password" name="pwCheck" value={ this.state.pwCheck }
                onChange = { this.changeEvent.bind(this) } />

                <br />
                

                <InputLabel id="demo-simple-select-label">gender</InputLabel>
                <Select
                    labelId="demo-simple-select-label"
                    id="demo-simple-select"
                    value={this.state.gender}
                    onChange={this.handleChange}
                >
                    {genders.map((gender) => (
                        <MenuItem key={gender} value={gender}>
                            {gender}
                        </MenuItem>
                    ))}
                </Select>

                <br />
                photo : &nbsp;
                <input type="file" name="photo"
                onChange={this.imageUpload.bind(this)}
                ></input>

                <div>
                    <InputLabel id="demo-simple-select-label">photo</InputLabel>
                    <br />
                    <Upload 
                        batch={false}
                        multiple={true}
                        files={this.state.files}
                        onAdd={this.onAdd}
                        onRemove={this.onRemove}
                        onProgress={this.onProgress}
                        onStatusChange={this.onSatusChange}
                        withCredentials={false}
                        saveUrl={URL + '/member/upload'}
                        removeUrl={'https://demos.telerik.com/kendo-ui/service-v4/upload/remove'}
                        onChange={this.imageUpload.bind(this)}
                    />
                    <div className={'example-config'} style={{ marginTop: 20 }}>
                        <ul className={'event-log'}>
                            {
                                this.state.events.map(event => <li key={event}>{event}</li>)
                            }
                        </ul>
                    </div>
                    {
                        this.state.files.length ? 
                        <div className={'img-preview example-config'}>
                            <h3>photo previews</h3>
                            {
                                Object.keys(this.state.filePreviews)
                                    .map((fileKey, index) => (<img 
                                        src={this.state.filePreviews[fileKey]} 
                                        alt={index}
                                        style={{ width: 200, margin: 10 }} 
                                    />))
                            }
                        </div> : undefined
                    }
                </div>


                <br />
                

                <TextField id="standard-secondary" label="address" color="secondary" 
                type="text" name="address" value={ this.state.address }
                onChange = { this.changeEvent.bind(this) } />

                
                
                <TextField id="standard-secondary" label="addrdetail" color="secondary" 
                type="text" name="addrdetail" value={ this.state.addrdetail }
                onChange = { this.changeEvent.bind(this) } />

                <br />
                

                <TextField id="standard-secondary" label="phone" color="secondary" 
                type="text" name="hp" value={ this.state.hp }
                onChange = { this.changeEvent.bind(this) } />
                <br />
                
                <RippleBtn2 />
                </form>
            </div>
        );
    }

}

SignupPageComp.propTypes = {
    classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(SignupPageComp);
0
SOYEON
Top achievements
Rank 1
answered on 29 Jan 2021, 01:33 AM

uploadFile = e.affectedFiles[0].name;

i change

e.target.files[0] 

to

e.affectedFile[0].name;

 

but eclipse returns

 2021-01-29 10:26:27.741  WARN 10756 --- [io-9002-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'uploadFile' is not present]

 

 

imageUpload=(e)=>{
        uploadFile = e.affectedFiles[0].name;

       
        const memberFile = new FormData();
        memberFile.append("uploadFile",uploadFile);

        axios({
            method: 'post',
            url: URL + '/member/upload',
            data: memberFile,
            headers: {'Content-Type':'multipart/form-data'}
        }).then(response=>{
            alert(response.data.photoname+" => save as this name");

            this.setState({
                photoname: response.data.photoname
            })
        }).catch(err=>{
            console.log("photo upload error:"+err);
        })
    }

0
Stefan
Telerik team
answered on 29 Jan 2021, 01:51 PM

Hello,

Thank you for sharing the code.

Could you please share the specific issue, as from the post it is not clear the issue that occurs with the Upload?

Regards,
Stefan
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Tags
General Discussions
Asked by
SOYEON
Top achievements
Rank 1
Answers by
Stefan
Telerik team
SOYEON
Top achievements
Rank 1
Share this question
or