I am to send a picture from an android phone to a local web server on my computer. I'd like to save the picture to a folder on the local server. My plan is to write some kind of controller that takes care of the received picture and saves it. So basically I think I need to create a controller that takes in a parameter (the picture) and saves it to a folder at the server. I have been searching all over and haven't yet found what I'm looking for.
Therefore what I'd like to know is:
How is such a controller written.
I am currently using Apache Tomcat/7.0.39 web server, Spring MVC Framework through STS and my OS is Windows 7.
Aprreciate any help I can get! Code examples would be greatly appreciated.
Thank you,
Mat
Apache Commons FileUpload is pretty easy to use to process multipart form posts. I don't think I've used it with Spring MVC, but there are examples out there.
For a similar function (loading photos from Android to servlet), here's the Android client code I use (edited slightly for posting here):
URI uri = URI.create(// path to file);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
// several key-value pairs to describe the data, one should be filename
entity.addPart("key", new StringBody("value"));
File inputFile = new File(photoUri.getPath());
// optionally reduces the size of the photo (you can replace with FileInputStream)
InputStream photoInput = getSizedPhotoInputStream(photoUri);
entity.addPart("CONTENT", new InputStreamBody(photoInput, inputFile.getName()));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uri);
HttpContext localContext = new BasicHttpContext();
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost, localContext);
and here's the code to receive it. First, be sure to tag your servlet class as supporting multipart messages:
#MultipartConfig
public class PhotosServlet extends HttpServlet
and then the relevant part of the body:
HttpEntity entity = new InputStreamEntity(request.getPart("CONTENT").getInputStream(), contentLength);
InputStream inputFile = entity.getContent();
// string extension comes from one of the key-value pairs
String extension = request.getParameter(//filename key);
// first write file to a file
File images = new File(getServletContext().getRealPath("images"));
File filePath = File.createTempFile("user", extension, images);
writeInputDataToOutputFile(inputFile, filePath); // just copy input stream to output stream
String path = filePath.getPath();
logger.debug("Wrote new file, filename: " + path);
Hope it helps.
This is the solution I went with using STS with MVC Framework template:
The controller:
#Controller
public class HomeController {#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("name") String name, #RequestParam("file") MultipartFile file) throws IOException {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
FileOutputStream fos = new FileOutputStream(
"C:\\Users\\Mat\\Desktop\\image.bmp");
try {
fos.write(bytes);
} finally {
fos.close();
}
return "works";
} else {
return "doesn't work";
}
}
}
The .jsp file (the form):
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Upload a file please</title>
</head>
<body>
<h1>Please upload a file</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
Related
I have an html template file, lets call it index.tpl, which I want to process with a java servlet.
This is what index.tpl looks like:
<html>
<body>
<h1> Pet profile - {pet.name} </h1>
<p> age {pet.age} </p>
etc.
</body>
</html>
How can I make a servlet that takes this html as an input, processes it, and sends it back to the browser?
The user journey is basically:
1.User types something like webAppDomain.com/index.tpl?id=1
2.Servlet processes index.tpl and shows the filled template to the user
I'm specifically interested in knowing how the servlet can take the html code as an input to process.
I've tried searching for some way to do this, but I've literally just picked up servlets and I'm a bit lost.
In your servlet code for the servlet at "/", in the doGet() method read the path to find your template file:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String pathFromUrl = request.getPathInfo();
String filePath = BASE_PATH + "/" + pathFromUrl;
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
String fileContent = new String (bytes);
String id = request.getParameterByName("id");
Pet pet = // get pet with id
// TODO modify fileContent with pet content
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().write(fileContent);
response.getWriter().flush();
}
you can try this by using Velocity
add Velocity dependency
put this in your index.tpl
String templateFile = "index.tpl";
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.init();
Template template = velocityEngine.getTemplate(templateFile);
VelocityContext context = new VelocityContext();
context.put("pet.name", "Fluffy");
context.put("pet.age", 5);
StringWriter writer = new StringWriter();
template.merge(context, writer);
String result = writer.toString();
set content for response
response.setContentType("text/html");
response.getWriter().write(result);
I'm having an issue where I am trying to download a simple "text/plain" file in a spring controller method. I'm getting the text that I exactly want in the web tools response when running the app, which is "test". The response headers in the web developer tools are as follows:
Content-disposition: attachment; filename=file.txt
Content-type: text/plain
Content-length: 4
Length is 4 since that's the number of bytes that the text "test" is. In the controller, I have produces = MediaType.TEXT_PLAIN_VALUE. When I click the associated button in the application to download the file, however, rather than showing the download in the web browser, the download is made to the disk because the file.txt actually shows up in my project's workspace in intellij (which I'm using for my IDE). So, my question is how do I get the download to occur in the web browser, meaning what happens when you click on the 'Download Source Code' button at the following link https://howtodoinjava.com/spring-mvc/spring-mvc-download-file-controller-example/, rather than the file downloading to my workspace/disk?
The support methods/classes look like the following:
public class TextFileExporter implements FileExporter {
#Override
public Path export(String content, String filename) {
Path filepath = Paths.get(filename);
Path exportedFilePath = Files.write(filepath, content.getBytes(),
StandardOpenOption.CREATE);
}
}
public interface FileExporter {
public Path export(String content, String filename);
}
The controller at hand is the following:
#GetMapping(value="downloadFile")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
String filename = "example.txt";
String content = "test";
Path exportedpath = fileExporter.export(content, filename);
response.setContentType(MediaType.TEXT_PLAIN_VALUE);
Files.copy(exportedpath, response.getOutputStream());
response.getOutputStream.flush();
}
Try using directly the Response entity to return an InputStreamResource
#RequestMapping("/downloadFile")
public ResponseEntity<InputStreamResource> downloadFile() throws FileNotFoundException {
String filename = "example.txt";
String content = "test";
Path exportedpath = fileExporter.export(content, filename);
// Download file with InputStreamResource
File exportedFile = exportedPath.toFile();
FileInputStream fileInputStream = new FileInputStream(exportedFile);
InputStreamResource inputStreamResource = new InputStreamResource(fileInputStream);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName)
.contentType(MediaType.TEXT_PLAIN)
.contentLength(exportedFile.length())
.body(inputStreamResource);
}
As #chrylis -cautiouslyoptimistic said try avoiding using low level objects, let it handle it by Spring itself
I want to create a txt file in my Servlet and automatically download it at the client side when client requests. I have below code to write to a txt, but it gives access denied error in Netbeans IDE using glassfishserver. How can I do it?
//File creation
String strPath = "C:\\example.txt";
File strFile = new File(strPath);
boolean fileCreated = strFile.createNewFile();
//File appending
Writer objWriter = new BufferedWriter(new FileWriter(strFile));
objWriter.write("This is a test");
objWriter.flush();
objWriter.close();
Its not a thing you do it in JSP. You better have a Servlet and just create a Outputstream and put your text in it. Then flush that stream into the HttpServletResponse.
#WebServlet(urlPatterns = "/txt")
public class TextServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment; filename=\"example.txt\"");
try {
OutputStream outputStream = response.getOutputStream();
String outputResult = "This is Test";
outputStream.write(outputResult.getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Remember you need to set the content-type text/plain and a Content-Disposition header that mentions filename and tells broswer that it should be downloaded as file attachment.
This is what Content-Disposition header is about in concise description
In a regular HTTP response, the Content-Disposition response header is
a header indicating if the content is expected to be displayed inline
in the browser, that is, as a Web page or as part of a Web page, or as
an attachment, that is downloaded and saved locally.
If you are a beginner. You may like to learn more about from this
What is HTTP, Structure of HTTP Request and Response?
How a Servlet Application works
Difference Between Servlet and JSP
I am trying to upload an image to a mysql database using a SOAP web service developed with Java in GlassFish server. This web service is being consumed by a client in JSP. I've searched a lot, but couldn't find a proper answer.
Could anyone help me? Thanks in advance!
This is the full answer of my question. I don't believe that you will have problems with .jsp page, you just need to create a form with inputs as you wish. The code that handles the upload is below:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = "";
String comment = "";
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
} else {
if ("comment".equals(item.getFieldName())) {
comment = item.getString();
// Whatever you have to do with the comment
}
}
}
addPhoto((int) request.getSession().getAttribute("id"), UPLOAD_DIRECTORY + File.separator + name , comment);
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message","Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
You have to create the client code to consume the web service using JAX-WS or another framework like CXF, Axis or Spring WS.The client code will be in the controller of your application. JSP will act as view to send the data to send to the service to the controller, then the controller will interact with the web service.
Here's a skeleton of the JSP and the controller:
<form action="${request.contextPath}/path/to/controller" method="POST" enctype="multipart/form-data">
File to upload:
<input type="file" name="fileData" />
<br />
<!-- probably more fields, depending on your requirements... -->
<input type="submit" value="Upload file">
</form>
Controller code (since you don't specifi an specific framework to be used, I'm using plain Servlet):
#WebServlet("/path/to/controller")
public class FileUploadToWSServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//consume the data from JSP
//pass the data received from JSP
//to send it to consume the JAX-WS service
}
}
Trying to consume the web service directly from JSP is doable through scriptlets but its usage should be avoided, so this approach is not recommended and is not part of my answer.
hi am create excel sheet using extends AbstractExcelView i write following code
public ModelAndView exportToExcel(HttpServletRequest request, #RequestParam Map<String, ? extends Object> params, ShipmentDetailsSearchInput shipmentDetailsInputType) throws ParseException
{
Map<String, Object> excelMap = new HashMap<String, Object>();
return new ModelAndView("ExcelReport", UIErrorMessages.DATA, excelMap);
}
i wont to get Ajax response that file download success in Extjs Ajax response because ModelAndView Not Give any response in submit ajax call.
how to we can write restful excel-download component without modeandview in spring 3
If you want to create dynamic excel file sheet then you can use Apache POI. You can create ,update and modify excel sheet.
I am using Apache POI to generate an excel file and filling it.
More details can be found here, example link and another example link.
Please note you don't have to use Ajax and can directly map a GET request to the method exportToExcel.
To avoid return ModelAndView object, you can directly write the generated file into response stream.
You will have to set ContentType and HttpServletResponse header to appropriate format,
as show below:
public void exportToExcel(HttpServletRequest request, #RequestParam Map<String, ? extends Object> params, ShipmentDetailsSearchInput shipmentDetailsInputType,
HttpServletResponse response) throws ParseException
{
// Map<String, Object> excelMap = new HashMap<String, Object>();
// return new ModelAndView("ExcelReport", UIErrorMessages.DATA, excelMap);
String fileName = "RandomFile";
HttpHeaders header = new HttpHeaders();
header.setContentType(new MediaType("application", "vnd.ms-excel"));
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
//method to create Workbook
Workbook book = createFileAndFillDetails();
try {
book.write(response.getOutputStream());
}
catch (IOException e) {
//Handle error
}
}
If you have to use Ajax there are no direct solutions. The choices you are left with are :
1) Using a hidden frame as mentioned in How to download file from server using jQuery AJAX and Spring MVC 3
2) Redirect the browser
3) Don't use ajax at all, because ajax/jquery is not going to be useful to handle this scenario. A url with GET request offers easy approach as mentioned in the other solution proposed.
If I undestand correctly your question, you want to create an excel spreadsheet when an asynchronous call is made to your controller (so via AJAX).
First of all, I don't think it's a good idea to download file via ajax call. If your problem is a long time to generate your excel spreadsheet, I suggest you to generate it asynchronously (in a separate thread for example) and than to download the generated file via a classical GET request.
I'm doing something similar in a web application that generate a large CSV file. I'm using this simple method to get the generated file:
#RequestMapping(value = "/file", method = RequestMethod.GET)
public void getFile(
#RequestParam(value = "token", required = false) String token,
HttpServletResponse response) throws Exception {
// my logic...
String formattedDataString = exportTask.getResults());
response.setHeader("Content-Disposition", "attachment; filename=\""
+ exportTask.getExportFileName() + "\"");
response.setContentType("text/plain; charset=utf-8");
IOUtils.copy(
new ByteArrayInputStream(formattedDataString.getBytes()),
response.getOutputStream());
response.flushBuffer();
}
}
In my page I have a simple link like this:
<c:url var="fileUrl" value="results/file">
<c:param name="token" value="${token}" />
</c:url>
<a href='<c:out value="${fileUrl}" />'>Get File</a>
In my case the token param identify the generated file, that is stored in the local DB.
However, if you still want to use ajax, I suggest you to take a look to #ResponseBody annotation.