java上传图片或文件

转载至:http://www.xdx97.com/#/single?bid=8b351a73-922c-eadc-512e-9e248a3efde9

前端通过form表单用post方式提交文件,后台进行保存处理。此处省略较多注释及其他功能,仅保留上传文件功能,建议阅读原文学习。

前端:

<!DOCTYPE html>
<html>
<head>
<meta name="content-type" content="text/html; charset=UTF-8">
<title>发布商品</title>
</head>
<body>
    <form action="../com/yh/myServlet/AddGoodsServlet"
        enctype="multipart/form-data" method="post">
        上传文件:<input type="file" name="picture"> <br/>
        <input type="submit" value="提交">
    </form>
</body>
</html>

 

后端:

package com.yh.myServlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class AddGoodsServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html;charset=utf-8");

        String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
        savePath = savePath.replace("\\", "\\\\");
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdir();
        }
        InputStream in = null;
        FileOutputStream out = null;
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");

            List<FileItem> list = upload.parseRequest(request);
            for (FileItem item : list) {
                String filename = item.getName();
                if (filename == null || filename.trim().equals("")) {
                    continue;
                }
                filename = filename.substring(filename.lastIndexOf(".") + 1);
                filename = UUID.randomUUID().toString() + "." + filename;
                out = new FileOutputStream(savePath + "\\" + filename);
                byte[] buffer = new byte[1024];
                int len = 0;
                in = item.getInputStream();
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                item.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            in.close();
            out.close();
        }
    }
}

 

上一篇:C# 操作文件常用的方法


下一篇:Nginx日志切割