文件上传

五迷三道 提交于 2020-03-16 13:47:21

某厂面试归来,发现自己落伍了!>>>

angular部分

html部分 `<input type="file" (change)="onFileChanged($event)">

  <button (click)="onUpload()">上传</button>`

ts部分

`selectedFile: string;‘

onFileChanged(event) { this.selectedFile = event.target.files[0]; //this.onUpload(); }

onUpload() { // upload code goes here

const uploadData = new FormData();

uploadData.append('uploadfile', this.selectedFile); this.http.post('http://localhost/manage/uploadPic',uploadData).subscribe( (data:any)=>{ // alert(data); console.log(JSON.stringify(data)); },(err:HttpErrorResponse)=>{ console.log(err.message); } )

}`

服务器端部分 `

’ @PostMapping("uploadPic") @ResponseBody public String uploadPic(MultipartFile uploadfile) throws Exception{

  String finename=uploadfile.getOriginalFilename();
  String suffixname=uploadfile.getOriginalFilename().substring(finename.lastIndexOf("."));

  finename=String.valueOf(System.currentTimeMillis())+suffixname;

  String filepath="d:/springbootupload/";

  File tf=new File(filepath);
  if(!tf.exists()){
      tf.mkdir();
  }



    try {
        uploadfile.transferTo(new File(filepath+finename));
        return finename;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    }

return null; }`

applicatin.properties映射本地路径
`spring.resources.static-locations=file:D://springbootupload

spring.mvc.static-path-pattern=/**`

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!