image upload

工作遇到上傳圖片功能

使用JDK8、tomcat8、Servlet3

因為需要支援IE8跟IE9,因此沒有用formData

JSP

<h5>上傳圖片</h5>
<div>
    <input type="file" class="form-control" id="img_id" name="img_name" style="width:80%;" multiple="multiple" accept="image/*">
</div>
<div id="upload" style="display:none;">Uploading..</div>
<h5>照片顯示</h5>
<div id="img">
    <div class="preview" style="display:inline;"></div>
</div>

multiple=”multiple”支援多圖片上傳,HTML5有支援
換言之,IE10、chrome6.0、firefox3.6、safari5.0、opera11這些版本以上皆支援

JS

    $('input[type="file"]').ajaxfileupload({
        'action': 'XXXServlet',	      	
        'params' : {ajaxAction : 'UPLOAD', AAA : aaa, BBB : bb,
        'onComplete': function(response, data, textStatus, xhr) {	        
            //寫自己要的邏輯
        },
        'onStart': function() {
            //寫自己要的邏輯
        },
        'onCancel' : function() {
            //寫自己要的邏輯
        }
    });

一般都是圖片上傳成功後,再存資料
因為上傳有機會會掉封包,所以檔案傳輸可能會fail

JAVA

package servlet.fileUpload;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

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

/**
 * Servlet implementation class PicServlet
 */
@WebServlet(name="/PicServlet", urlPatterns = "/view/PicServlet")
public class PicServlet extends HttpServlet {
	//http://localhost:8080/Servlet3.0/view/
	private static final long serialVersionUID = 1L;
    
    public PicServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		response.sendRedirect("picUpload.jsp");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Properties prop = new Properties();
		String propFileName = "config.properties";

		InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

		if (inputStream != null) {
			prop.load(inputStream);
		} else {
			throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
		}
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		
        if (isMultipart) {
        	// Create a factory for disk-based file items
        	FileItemFactory factory = new DiskFileItemFactory();
        	// Create a new file upload handler
        	ServletFileUpload upload = new ServletFileUpload(factory);
 
            try {
            	// Parse the request
				List items = upload.parseRequest(request);
				Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();
                    if (!item.isFormField()) {
                        String fileName = item.getName();	 
                        //String root = getServletContext().getRealPath("/");
                        String root = prop.getProperty("rootPath");
                        File path = new File(root + "/picUploads");
                        if (!path.exists()) {
							path.mkdirs();
                        }
 
                        File uploadedFile = new File(path + "/" + fileName);
                        System.out.println(uploadedFile.getAbsolutePath());
                        item.write(uploadedFile);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
	}

}


在〈image upload〉中有 2 則留言

留言功能已關閉。