javaweb 上传文件使用NIO进行读写

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.UUID;

@Controller
public class MailSend {

    @Value("${uploadpath:}")
    private String uploadpath;

    @RequestMapping("/uploadfile")
    @ResponseBody
    public Object uploadfile(@RequestParam("file")MultipartFile file){
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = (FileInputStream) file.getInputStream();
            fos = new FileOutputStream(new File(uploadpath + "\\" + UUID.randomUUID().toString() +"_" +file.getName()));

            FileChannel inChannel = fis.getChannel();
            FileChannel outChannel = fos.getChannel();

            int capacity = 1024;
            ByteBuffer buffer = ByteBuffer.allocate(capacity);
            int len = -1;
            while( (len=inChannel.read(buffer))!=-1 ){
                buffer.flip();

                int length = 0;
                while (( length=outChannel.write(buffer) )!=0){

                }
                buffer.clear();
            }
            inChannel.close();
            outChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaWeb中实现文件上传可以使用多种技术和框架。其中一种常用的方法是使用Servlet和Apache Commons FileUpload库。 首先,你需要在JSP页面中创建一个表单,设置表单的enctype属性为"multipart/form-data",这样才能支持文件上传。表单中需要包含一个或多个<input type="file">标签,用于选择要上传的文件。同时,你也可以添加其他的表单字段,如用户名等。\[2\] 接下来,在Servlet中处理文件上传。你可以使用Apache Commons FileUpload库中的ServletFileUpload类来处理上传的文件数据。通过调用parseRequest(HttpServletRequest)方法,你可以将表单中的每个输入项封装成一个FileItem对象,并以List的形式返回。然后,你可以遍历这个List,获取每个FileItem对象的信息,如文件名、文件大小等。\[3\] 在处理文件上传时,你可以根据需要进行一些验证和处理操作,如检查文件类型、文件大小限制等。然后,你可以将文件保存到服务器的指定位置,可以是本地文件系统或数据库等。 以下是一个简单的示例代码,演示了如何在JavaWeb中实现文件上传: ```java @WebServlet("/upload") @MultipartConfig public class UploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 创建一个文件上传处理器 ServletFileUpload upload = new ServletFileUpload(); try { // 解析请求,获取文件项列表 List<FileItem> items = upload.parseRequest(request); // 遍历文件项列表 for (FileItem item : items) { // 判断当前项是否为文件 if (!item.isFormField()) { // 获取文件名 String fileName = item.getName(); // 保存文件到指定位置 item.write(new File("/path/to/save/" + fileName)); } } // 文件上传成功 response.getWriter().println("文件上传成功"); } catch (Exception e) { // 文件上传失败 response.getWriter().println("文件上传失败"); e.printStackTrace(); } } } ``` 在这个示例中,我们使用了@WebServlet注解将Servlet映射到"/upload"路径。通过@MultipartConfig注解,我们告诉Servlet容器该Servlet支持文件上传。 在doPost方法中,我们创建了一个ServletFileUpload对象,并调用parseRequest方法解析请求,获取文件项列表。然后,我们遍历文件项列表,判断每个项是否为文件,如果是文件,则获取文件名并保存到指定位置。 最后,我们根据文件上传的结果返回相应的信息给客户端。 请注意,这只是一个简单的示例,实际的文件上传过程可能需要更多的处理和验证操作,如文件大小限制、文件类型检查等。你可以根据自己的需求进行相应的扩展和优化。 希望这个示例能帮助你理解如何在JavaWeb中实现文件上传。如果你有任何进一步的问题,请随时提问。 #### 引用[.reference_title] - *1* [【JavaWeb】文件的上传](https://blog.csdn.net/wang_qiu_hao/article/details/127177250)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [JavaWeb--文件的上传](https://blog.csdn.net/zhoulv163/article/details/126006904)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值