1. 程式人生 > >檔案上傳前後臺程式碼

檔案上傳前後臺程式碼

後臺實現

springMVC-servlet.xml

<!-- 設定上傳檔案最大值 1M=1*1024*1024(B)=1048576 bytes -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576" />
    </bean>

controller

@RequestMapping(value = "/upload")
    @ResponseBody
    public String upload(@RequestParam("filename") MultipartFile file) {
       System.out.println("qewqeqwwqe");
        if (file.isEmpty()) {
            return "檔案為空";
        }
        // 獲取檔名
        String fileName = file.getOriginalFilename();
     
        // 獲取檔案的字尾名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
      
        // 檔案上傳路徑
        String filePath = "d:/roncoo/ttt/";
        // 解決中文問題,liunx 下中文路徑,圖片顯示問題
        //fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        // 檢測是否存在目錄
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return "上傳成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上傳失敗";
    }

 

前臺vue

<div>
          <input type="file" @change="getFile($event)" /><button @click="upload">檔案上傳</button>
          <div>{{ result }}</div>
          <div v-show="uping==1">正在上傳中</div>
        </div>

 export default {
    name: 'hello',
    data () {
      return {
        upath: '',  //檔案上傳
        result: '',
        uping: 0
             }
           },
    methods: {
          upload: function () {
        //console.log(this.upath);
        var zipFormData = new FormData();
        zipFormData.append('filename', this.upath);//filename是鍵,file是值,就是要傳的檔案,test.zip是要傳的檔名
        let config = { headers: { 'Content-Type': 'multipart/form-data' } };
        this.uping = 1;
        this.$http.post('http://localhost:8080/hjsk/upload', zipFormData,config).then(function (response) {
          console.log(response);
          console.log(response.data);
          console.log(response.bodyText);
           
          var resultobj = response.data;
          this.uping = 0;
          this.result = resultobj.msg;
        });
      },
      getFile: function (even) {
        this.upath = event.target.files[0];
      }
           
     }

<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
        
        </dependency>