文件上傳

文件上傳是指將本地計(jì)算機(jī)上的文件傳輸?shù)椒?wù)器上的過程。SpringMVC提供了MultipartResolver接口來處理文件上傳。下面是實(shí)現(xiàn)文件上傳的步驟:

配置SpringMVC

在SpringMVC的配置文件中,需要添加以下配置來啟用文件上傳功能:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="5242880"/>
</bean>

創(chuàng)建文件上傳表單

在前端頁面中,需要?jiǎng)?chuàng)建一個(gè)文件上傳的表單,通過<form>標(biāo)簽設(shè)置enctype屬性為"multipart/form-data",以支持文件上傳:

<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit" value="上傳文件"/>
</form>

處理文件上傳請(qǐng)求

在Controller中,通過使用@RequestParam注解來接收上傳的文件:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
    // 處理文件上傳邏輯
    return "uploadSuccess";
}

保存上傳文件

在handleFileUpload方法中,可以通過MultipartFile的方法來獲取上傳文件的相關(guān)信息,如文件名、大小等。可以將文件保存到指定位置:

if (!file.isEmpty()) {
    try {
        byte[] bytes = file.getBytes();
        // 保存文件到指定位置
        String filePath = "/path/to/save/" + file.getOriginalFilename();
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
        stream.write(bytes);
        stream.close();
        return "uploadSuccess";
    } catch (Exception e) {
        e.printStackTrace();
        return "uploadFail";
    }
} else {
    return "uploadFail";
}

文件下載

文件下載是指將服務(wù)器上的文件傳輸?shù)奖镜赜?jì)算機(jī)上的過程。SpringMVC可以通過設(shè)置響應(yīng)頭信息來實(shí)現(xiàn)文件下載的功能。

配置文件下載

在SpringMVC的配置文件中,需要添加以下配置來啟用文件下載功能:

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="defaultContentType" value="text/html"/>
    <property name="favorPathExtension" value="true"/>
    <property name="mediaTypes">
        <map>
            <entry key="html" value="text/html"/>
            <entry key="pdf" value="application/pdf"/>
            <entry key="xls" value="application/vnd.ms-excel"/>
            <entry key="xml" value="application/xml"/>
        </map>
    </property>
</bean>

處理文件下載請(qǐng)求

在Controller中,可以通過設(shè)置響應(yīng)頭信息來實(shí)現(xiàn)文件下載的功能:

@RequestMapping(value = "/download", method = RequestMethod.GET)
public void downloadFile(HttpServletResponse response) {
    String fileName = "example.pdf";
    String filePath = "/path/to/file/" + fileName;
    
    File file = new File(filePath);
    if (file.exists()) {
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.flush();
            os.close();
            bis.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

總結(jié)

通過使用SpringMVC框架,我們可以輕松實(shí)現(xiàn)文件上傳和下載的功能。在文件上傳方面,需要配置MultipartResolver和創(chuàng)建文件上傳表單,并處理文件上傳請(qǐng)求;在文件下載方面,需要配置ContentNegotiatingViewResolver和處理文件下載請(qǐng)求。以上是SpringMVC文件上傳下載的基本實(shí)現(xiàn)步驟,開發(fā)者可以根據(jù)實(shí)際需求進(jìn)行擴(kuò)展和優(yōu)化。