java 文件上传

Posted baowangze

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 文件上传相关的知识,希望对你有一定的参考价值。

package servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import entit.News;
import service.NewService;
import service.impl.NewServiceImpl;

/**
 * Servlet implementation class newsServlet
 */
@WebServlet("/uploadFileServlet")
public class newsServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public newsServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String uplaodPath = null;
        response.setCharacterEncoding("utf-8");
        News news = new News(); 
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        boolean flag = upload.isMultipartContent(request);
        if (flag) { // 证明文件上传请求
            try {
                // 获取的是所有的表单元素 包括普通元素和文件元素
                List<FileItem> items = upload.parseRequest(request);
                // List<FileItem> 是一个元素吗? 是4个??有可能N个??? 遍历!!!!
                Iterator<FileItem> its = items.iterator();
                while (its.hasNext()) { // 遍历集合
                    // 获取一个一个的元素
                    FileItem item = its.next();
                    if (item.isFormField()) { // 普通字段
                        String fileName = item.getFieldName(); // 获取name属性值
                        if (fileName.equals("id")) {
                            news.setNewsid(Integer.parseInt(item.getString("utf-8")));
                        } else if (fileName.equals("title")) {
                            news.setNewstitle(item.getString("utf-8"));
                        } else if (fileName.equals("author")) {
                            news.setNewssummary(item.getString("utf-8"));
                        }
                    } else { // 文件元素
                        // 获取服务器所在的位置
                        uplaodPath = request.getSession().getServletContext().getRealPath("uploadFiles/");
                        
                        File file = new File(uplaodPath);
                        if (!file.exists()) { // 如果创建文件夹不存杂 则创建
                            file.mkdirs();
                        }
                        // 获取上传文件的名称
                        String fileName = item.getName();
                        // 用户有可能不上传文件
                        if (!fileName.equals("") && fileName != null) {
                            File uploadFile = new File(fileName); // 获取上传文件
                            File saveFile = new File(uplaodPath,
                                    uploadFile.getName());// 拼接文件位置
                            // 真正的上传
                            item.write(saveFile);
                            news.setNewspic(uploadFile.getName()); // 给对象赋值
                        }

                    }
                }
                NewService service = new NewServiceImpl();
                int num = service.addNew(news);
                if (num > 0) {
                    System.out.println(uplaodPath);
                } else {
                    System.out.println("新增失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            System.out.println("不是文件上传请求!");
        }
    }
}

使用的时候需要导入俩个jar

以上是关于java 文件上传的主要内容,如果未能解决你的问题,请参考以下文章

android的自带的httpClient 怎么上传文件

Java itext为pdf 文件添加水印核心功能代码片段

nzSQLException 读取超时错误

将存储在内存中的文件上传到s3

JS创建文件并上传服务器

ajaxFileUpload上传带参数文件及JS验证文件大小