package org.geopublishing;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class ShapeConvert extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String TMP_DIR_PATH = "C:\\tmp";
private File tmpDir;
private static final String DESTINATION_DIR_PATH = "/WEB-INF/files";
private File destinationDir;
public void init(ServletConfig config) throws ServletException {
super.init(config);
tmpDir = new File(TMP_DIR_PATH);
if (!tmpDir.isDirectory()) {
throw new ServletException(TMP_DIR_PATH + " is not a directory");
}
//String realPath = getServletConfig().getServletContext().getRealPath("");
String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
if (!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH
+ " is not a directory");
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
out.println();
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
/*
* Set the size threshold, above which content will be stored on disk.
*/
fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1
/*
* Set the temporary directory to store the uploaded files of size above
* threshold.
*/
fileItemFactory.setRepository(tmpDir);
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
/*
* Parse the request
*/
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
/*
* Handle Form Fields.
*/
if (item.isFormField()) {
out.println("File Name = " + item.getFieldName()
+ ", Value = " + item.getString());
} else {
// Handle Uploaded files.
out.println("Field Name = " + item.getFieldName()
+ ", File Name = " + item.getName()
+ ", Content type = " + item.getContentType()
+ ", File Size = " + item.getSize());
/*
* Write file to the ultimate location.
*/
File file = new File(destinationDir, item.getName());
out.println(destinationDir);
item.write(file);
}
out.close();
}
} catch (FileUploadException ex) {
log("Error encountered while parsing the request", ex);
} catch (Exception ex) {
log("Error encountered while uploading file", ex);
}
}
}
Duvida com servlet
V
Fala ai galera , sou nenem no desenvolvimento web :) e estou prescisando de criar uma pagina q realiza upload de um arquivo com formato .shp. Achei na net este tutorial http://www.jsptube.com/servlet-tutorials/servlet-file-upload-example.html copie compilei tudo direitinho , MAS o tomcat some com o arquivo que faço upload nao consiguo encontrar em lugar nenhum.ALguem poderia me dar uma luz
Obs.: segue anexo o codigo do meu projeto
4 Respostas
olá amigo,
veja nessa linha
private static final String DESTINATION_DIR_PATH = "/WEB-INF/files";
Vc está especificando que o destino é a pasta web-inf, onde na realidade a pasta web inf está contida em um war ou ear…
mude o destino do arquivo para outro diretorio ex:
//pega o diretorio da aplicação dentro de webApp
String realPath = getServletConfig().getServletContext().getRealPath();
Tente isso:
Fallow
V
Muito Obrigado HUUAHUAHAUHAUHAUHAUHAUHAUAHU A PARADA FUNCIONOU 8) UFA !!! Mais uma pergunta como direciono o arquivo para uma pasta especifica dentro da aplicaçao ???
Você pode colocar a url do diretório que pretende salvar.
String realPath = "C:\\Pasta-Qualquer\\Outra-Pasta";
Desde que a sua aplicação tenha permissão de criar no diretório específico.
V
Valew cara muito obrigado!!!
Criado 29 de dezembro de 2010
Ultima resposta 30 de dez. de 2010
Respostas 4
Participantes 3