Jakarta FileUpload + Banco de Dados

1 resposta
R

Olá, estou procurando uma forma de salvar um documento num banco de dados via web.
Nessas pesquisas descobri o FileUpload e fiz um "programa-brinquedo" pra pegar as manhas dele, é bem simplezinho.

Página:

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>File Upload</title>
</head>
<body>
	<form method="POST" action="servletSave" enctype="multipart/form-data">
		<input type="file" name="archive">		  
		<input type="submit">  		
	</form>
</body>
</html>

Servlet:

import ....

public class ServletSave extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// Check that we have a file upload request
		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);
			// Parse the request
			try {
				List /* FileItem */ items = upload.parseRequest(request);
				Iterator iter = items.iterator();
				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();
					//Quer dizer q eh um arquivo
					if (!item.isFormField()) {
					    String fieldName = item.getFieldName();
					    String fileName = item.getName();
					    if (fileName != null) {
					        fileName = FilenameUtils.getName(fileName);
					    }
					    String contentType = item.getContentType();
					    boolean isInMemory = item.isInMemory();
					    long sizeInBytes = item.getSize();
					    System.out.println("Field Name: " + fieldName + "\n" +
					    				   "File Name: " + fileName + "\n" +
					    				   "Content Type: " + contentType + "\n" +
					    				   "Is In Memory: " + isInMemory + "\n" + 
					    				   "Size in Bytes: " + sizeInBytes);
					    File uploadedFile = new File("C:/"+fileName);
					    item.write(uploadedFile);
					}
				}	
			} catch (FileUploadException e) {
				System.out.println(e.getMessage());
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
	}
}

Nesse código consigo salvar o arquivo q eu desejo em C:/

Tenho dois problemas:
1)Eu acho q meu problema real eh mais complexo, eu tenho q salvar o arquivo no BD, não tenho idéia de como fazê-lo

2)Estou usando jquery(framework ajax) no meu programa original, e eu não sei como dizer q o encytype="multipart/form-data", alguem tem exemplos de uso de jquery + servlet + fileUpload?

Grato desde já!

1 Resposta

R

up

Criado 27 de novembro de 2008
Ultima resposta 28 de nov. de 2008
Respostas 1
Participantes 1