---
# System prepended metadata

title: h1 Java web 練習code

---

# h1 Java web 練習code
Uploads.java

package cc.openhome;

import java.io.*;
import java.time.Instant;

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

@MultipartConfig(location="c:/workspace")
@WebServlet("/uploads")

public class Uploads extends HttpServlet  {
	
	@Override
	protected void doPost(
		HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
			
		request.setCharacterEncoding("UTF-8");
		request.getParts()
				.stream()
				.filter(part->part.getName().startsWith("file"))//判斷檔案名稱開頭
				.forEach(this::write); //迭代Stream中的每個元素
	}


	private void write(Part part) {
		String submittedFileName = part.getSubmittedFileName();
		String ext = submittedFileName.substring(//取得副檔名
				submittedFileName.lastIndexOf('.'));
		
		try {
			part.write(String.format("%s%s", //使用時間毫秒數為主檔名
					Instant.now().toEpochMilli(),ext));
		} catch(IOException e) {
			throw new UncheckedIOException(e);
		}
			
	}
}	
	
