天天看點

用idea使用ssm架構進行檔案上傳

1.先導入兩個依賴包

<dependency>
   <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.2</version>
</dependency>
           

2.使用idea的時候可能會出現導入了依賴但是在lib檔案沒有出現的問題:可以去我前面的部落格看上面示範了步驟:添加lib進入class中

配置檔案:

<!-- 支援上傳檔案 -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 設定上傳檔案的最大尺寸為500MB -->
        <property name="maxUploadSize">
            <value>624288000</value>
        </property>
    </bean>
           

3.代碼

//上傳檔案
    //produces: 指定響應的類型
    @RequestMapping(value = "uploading", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public ResponseEntity<String> uploading(@RequestParam MultipartFile file, String acct) throws IOException {
        String imgName = file.getOriginalFilename();
        String suffix = imgName.substring(imgName.lastIndexOf("."));
        String path2 = FileHelperUtils.getPath();
        String path = "";
        if (acct != null && acct != "") {
            path = "D:/fileHelper" + "/" + acct + path2;
        } else {
            path = "D:/fileHelper" + path2;
        }
        InputStream inputStream = file.getInputStream();
        String pathName = SignFactory.getRandomFileName() + suffix;
        FileHelperUtils.saveFileFromInputStream(inputStream, path, pathName);
        return ResponseEntity.ok(StringUtils.isEmpty(acct)?path2+ pathName:"/" + acct + path2 + pathName);
    }
           

可以根據需要自行修改

4.網頁我用的是elementui的upload元件

<el-upload
                            class="upload-demo"
                            :action="uploading"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :file-list="fileList"
                            list-type="picture">
                        <el-button size="small" type="primary">點選上傳</el-button>
                        <div slot="tip" class="el-upload__tip">隻能上傳jpg/png檔案,且不超過500kb</div>
                    </el-upload>
           

裡面的屬性可以去elementui官網看這個是連接配接 elementui其中action後面的是我自己寫的方法位址

搞完就可以進行上傳了