YMP框架实现文件上传下载

潘兴朝
2023-12-01
JSP页面内容:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<form action="/hello/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="fileWrapper" >
    <input type="submit" value="上传">
</form>
<br>
<form action="/hello/download" method="post">
    <input type="submit" value="下载">
</form>
Controller
package net.jc.mytest6;

import net.ymate.platform.webmvc.IUploadFileWrapper;
import net.ymate.platform.webmvc.annotation.Controller;
import net.ymate.platform.webmvc.annotation.FileUpload;
import net.ymate.platform.webmvc.annotation.RequestMapping;
import net.ymate.platform.webmvc.annotation.RequestParam;
import net.ymate.platform.webmvc.base.Type;
import net.ymate.platform.webmvc.view.IView;
import net.ymate.platform.webmvc.view.View;
import net.ymate.platform.webmvc.view.impl.BinaryView;

import java.io.File;

/**
 * Hello Controller
 */
@Controller
@RequestMapping("/hello")
public class HelloController {


    //上传
    @RequestMapping(value = "upload",method = Type.HttpMethod.POST)     //Post请求
    @FileUpload
    public IView upload(@RequestParam IUploadFileWrapper fileWrapper) throws Exception {    //文件上传封装类 功能齐全
        String savepath = "F:\\Ideawork\\mytest-6\\src\\main\\webapp"+fileWrapper.getName();    //上传文件保存的路径
        File file = new File(savepath);
        fileWrapper.writeTo(file);                                                           //保存文件 参数为文件路径
        return View.textView("上传成功");                                                   //返回一个文本视图
    }
    //下载
    @RequestMapping(value = "/download",method = Type.HttpMethod.POST)       //Post请求
    public IView download() throws Exception {
        //返回二进制数据流视图
        // BinaryView:二进制数据流视图;
        // 下载文件,并重新指定文件名称
        //View.binaryView(new File("/temp/demo.txt")) .useAttachment("测试文本.txt");
        // = "binary:/temp/demo.txt:测试文本.txt"
        File file = new File("F:\\Ideawork\\mytest-6\\src\\main\\resources\\c3p0.properties");
        return BinaryView.bind(file).useAttachment("我的下载.properties");
    }
}

 类似资料: