I’m trying to program my application to upload images and then store them in a folder. It prints out the details of the file but doesn’t store it into the folder. I am following the User Guide and answers on here and I still don’t know what I am doing wrong?
import java.io.File;
import java.util.List;
import javax.servlet.ServletException;
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 UploadAvatarCommand implements Command {
@Override
public String execute(HttpServletRequest request,
HttpServletResponse response) {
DiskFileItemFactory factory = new DiskFileItemFactory();
String contextRoot = request.getServletContext().getRealPath("/");
factory.setRepository(new File(contextRoot + "WEB-INF/tmp"));
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
// Process form file field (input type="file").
System.out.println("Field name: " + item.getFieldName());
System.out.println("File name: " + item.getName());
System.out.println("File size: " + item.getSize());
System.out.println("File type: " + item.getContentType());
String fileName = item.getName();
try {
File saveFile = new File(fileName);
saveFile.createNewFile();
item.write(saveFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
try {
throw new ServletException("Cannot parse multipart request.", e);
} catch (ServletException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return "profile";
}
}
If you don’t have any error then this piece of code:
creates a new file with the name
fileName(that is only a simple name like “file.txt”) in the current folder.If you want to know which is your current workfolder try to print this:
so you can check if the files are here.
Then if you want to put files on the folder that you desire you can use:
and replace “/my/upload/folder” with the path of the folder you prefer.