Spring MVC storing files at RestService - java

Hi I am struggling in storing files at server I am new to spring MVC. Can anyone point me if I am doing it right or wrong.
What I have to do is take some files (text or binary) and store those in the storage device using Restservice.
public #ResponseBody String storeFiles(#RequestBody List<File> filenames, #PathVariable String dirname)
throws Exception {
// TODO Auto-generated method stub
Gson gson = new Gson();
String jsonList = gson.toJson(storeFiles.storeFilesToHitachi(filenames, dirname));
return jsonList;
}public Map<String, Integer> storeFilesToHitachi(List<File> filenames,String dirname) throws Exception{
Map<String, Integer> resultStored = new HashMap<String, Integer>();
if(checkDirAvailable(dirname) || createDirectoryAtHitachi(dirname)){
resultStored = storeFilenamesAtHitachi(filenames, dirname);
}
return resultStored;
}
public boolean createDirectoryAtHitachi(String dirname){
boolean isDirCreated = false;
try{
httpPutRequest.setHeader(HCPUtils.HTTP_AUTH_HEADER,"HCP "+ sEncodedUserName + ":" + sEncodedPassword);
hitachiURI = constructURLForCreateDir(dirname);
httpPutRequest.setURI(hitachiURI);
HttpResponse httpCreateDirResp = httpClient.execute(httpPutRequest);
int responseCode = httpCreateDirResp.getStatusLine().getStatusCode();
if(responseCode == 201) {
isDirCreated = true;
logger.info("A directory by the name "+ dirname +" has been created" );
}
logger.info(responseCode);
}
catch(Exception e){
logger.error("Unable to create directory:" + dirname + e.getMessage());
}
return isDirCreated;
}
public boolean checkDirAvailable(String dirname){
boolean dirAvailable = false;
try{
httpGetRequest.setHeader(HCPUtils.HTTP_AUTH_HEADER,"HCP "+ sEncodedUserName + ":" + sEncodedPassword);
hitachiURI = constructURLForCheckDir(dirname);
httpGetRequest.setURI(hitachiURI);
HttpResponse httpResponse = httpClient.execute(httpGetRequest);
int respCode = httpResponse.getStatusLine().getStatusCode();
if (respCode == 200){
dirAvailable = true;
logger.info("A directory named "+dirname +" is avaliable");
}
logger.info(respCode);
}
catch(Exception e){
logger.error("An exception occured while checking for "+dirname + e.getMessage());
}
return dirAvailable;
}
public Map<String, Integer> storeFilenamesAtHitachi(List<File> filenames,String dirname){
Map<String,Integer> resultMap = new HashMap<String, Integer>();
try{
File filename=null;
httpPutRequest.setHeader(HCPUtils.HTTP_AUTH_HEADER,"HCP "+ sEncodedUserName + ":" + sEncodedPassword);
Iterator<File> iter = filenames.iterator();
while(iter.hasNext()){
filename = iter.next();
hitachiURI = constructURLForStorFilesAtHitachi(dirname, filename);
httpPutRequest.setURI(hitachiURI);
receivedFile = new FileInputStream(filename);
httpPutRequest.setEntity(new InputStreamEntity(receivedFile, -1));
HttpResponse httpPutResponse = httpClient.execute(httpPutRequest);
int respCode = httpPutResponse.getStatusLine().getStatusCode();
resultMap.put(filename.getName(), respCode);
logger.info(resultMap);
logger.info("Response code is :"+respCode +" while saving " +filename +" in directory " +dirname);
}
}
catch(Exception e){
logger.error("Got the following exception while storing files:" +e.getMessage());
}
return resultMap;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Draft//EN">
<HTML>
<HEAD>
<TITLE>Error 415--Unsupported Media Type</TITLE>
</HEAD>
<BODY bgcolor="white">
<FONT FACE=Helvetica><BR CLEAR=all>
<TABLE border=0 cellspacing=5><TR><TD><BR CLEAR=all>
<FONT FACE="Helvetica" COLOR="black" SIZE="3"><H2>Error 415--Unsupported Media Type</H2>
</FONT></TD></TR>
</TABLE>
<TABLE border=0 width=100% cellpadding=10><TR><TD VALIGN=top WIDTH=100% BGCOLOR=white><FONT FACE="Courier New"><FONT FACE="Helvetica" SIZE="3"><H3>From RFC 2068 <i>Hypertext Transfer Protocol -- HTTP/1.1</i>:</H3>
</FONT><FONT FACE="Helvetica" SIZE="3"><H4>10.4.16 415 Unsupported Media Type</H4>
</FONT><P><FONT FACE="Courier New">The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.</FONT></P>
</FONT></TD></TR>
</TABLE>
</BODY>
</HTML>
My goal is to take list of files and store in particular directory at server.

Related

How to create a list of uploaded files in Spring Boot?

I want to create a list of uploaded files that are stored in a directory on my hard drive.
My Controller:
#Controller
class MyFileUploadController {
#RequestMapping(value = "/uploadOneFile", method = RequestMethod.GET)
public String uploadOneFileHandler(Model model) {
MyUploadForm myUploadForm = new MyUploadForm();
model.addAttribute("myUploadForm", myUploadForm);
return "uploadOneFile";
}
#RequestMapping(value = "/uploadOneFile", method = RequestMethod.POST)
public String uploadOneFileHandlerPOST(HttpServletRequest request, //
Model model, //
#ModelAttribute("myUploadForm") MyUploadForm myUploadForm) {
return this.doUpload(request, model, myUploadForm);
}
#RequestMapping(value = "/uploadMultiFile", method = RequestMethod.GET)
public String uploadMultiFileHandler(Model model) {
MyUploadForm myUploadForm = new MyUploadForm();
model.addAttribute("myUploadForm", myUploadForm);
return "uploadMultiFile";
}
#RequestMapping(value = "/uploadMultiFile", method = RequestMethod.POST)
public String uploadMultiFileHandlerPOST(HttpServletRequest request, //
Model model, //
#ModelAttribute("myUploadForm") MyUploadForm myUploadForm) {
return this.doUpload(request, model, myUploadForm);
}
private String doUpload(HttpServletRequest request, Model model, //
MyUploadForm myUploadForm) {
String description = myUploadForm.getDescription();
System.out.println("Description: " + description);
String uploadRootPath = request.getServletContext().getRealPath("upload");
System.out.println("uploadRootPath=" + uploadRootPath);
File uploadRootDir = new File("(directory)");
if (!uploadRootDir.exists()) {
uploadRootDir.mkdirs();
}
MultipartFile[] fileDatas = myUploadForm.getFileDatas();
List<File> uploadedFiles = new ArrayList<File>();
List<String> failedFiles = new ArrayList<String>();
for (MultipartFile fileData : fileDatas) {
String name = fileData.getOriginalFilename();
System.out.println("Client File Name = " + name);
if (name != null && name.length() > 0) {
try {
File serverFile = new File(uploadRootDir.getAbsolutePath() + File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(new
FileOutputStream(serverFile));
stream.write(fileData.getBytes());
stream.close();
uploadedFiles.add(serverFile);
System.out.println("Write file: " + serverFile);
} catch (Exception e) {
System.out.println("Error Write file: " + name);
failedFiles.add(name);
}
}
}
model.addAttribute("description", description);
model.addAttribute("uploadedFiles", uploadedFiles);
model.addAttribute("failedFiles", failedFiles);
return "uploadResult";
}
}
MyUploadForm
public class MyUploadForm {
private String description;
private MultipartFile[] fileDatas;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public MultipartFile[] getFileDatas() {
return fileDatas;
}
public void setFileDatas(MultipartFile[] fileDatas) {
this.fileDatas = fileDatas;
}
}
The User can upload his files on the uploadOneFile.html.
uploadOneFile.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:c="http://java.sun.com/xml/ns/javaee">
<head>
<meta charset="UTF-8">
<title>Upload One File</title>
</head>
<body>
<th:block th:include="/_menu"></th:block>
<h3>Upload single file:</h3>
<form th:object="${myUploadForm}" method="POST"
action="" enctype="multipart/form-data">
Beschreibung:
<br>
<input th:field="*{description}" style="width:300px;"/>
<br/><br/>
File to upload: <input th:field="*{fileDatas}" type="file"/>
<br/>
<input type="submit" value="Upload">
</form>
</body>
</html>
The uploaded files should then be displayed on the index page. Aswell it should be possible to download the files with just clicking on them.
I'm a beginner in Spring Boot so can you help me? If you need more informations let it me know.
You can create a table on that page (html layout you can choose as per design etc..)
Main logic can be:-
Get list of file's from the directory.
Have the names of files stored in a SET or LIST or something of your choice.
Pass the previous list onto UI using some model via the index page controller.
Render the list of files.
Upon clicking the particular file, call the endpoint to download file by name.
Some Code of initial interest could be like below:-
File directoryPath = new File("D:\\PATH\\OF\\DIRECTORY");
FileFilter textFilefilter = new FileFilter(){
public boolean accept(File file) {
boolean isFile = file.isFile();
if (isFile) {
return true;
} else {
return false;
}
}
};
//List of all the files (only files)
File filesList[] = directoryPath.listFiles(textFilefilter);
System.out.println("List of the files in the specified directory:");
for(File file : filesList) {
System.out.println("File-name: "+file.getName());
System.out.println("File-path: "+file.getAbsolutePath());
System.out.println("Size: "+file.getTotalSpace());
System.out.println(" ");
}

Java MimeMessage.saveChanges not calling updateMessageID

I am developing an application that needs to send an email via JavaMail with a specific Message ID.
I have extended the Java MimeMessage class to override the updateMessageID method so that I can set the message ID myself. The problem is that when I call the Transport.send(msg) method it is not calling the updateMessageID method. I thought perhaps I needed to call the saveChanges() method prior to calling Transport.send(msg). Even when I explicitly call msg.saveChanges() this does not trigger the updateMessageID method to be called.
What makes this all the more wacky is the fact that when I convert my test application to a JSP and run it, the Transport.send(msg) method DOES call the updateMessageID method.
Both my server and my webserver that I tested on are running jdk1.7.0_71.
Extended MimeMessage Class
package com.my.framework;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MYMimeMessage extends MimeMessage {
Session session;
private static int id = 0;
private static String messageID = null;
public MyMimeMessage(Session session) {
super(session);
this.session=session;
}
protected void updateMessageID() throws MessagingException {
System.out.println("Calling updateMessageID()");
setHeader("Message-ID", "<" + getUniqueMessageIDValue(session) + ">");
}
/* Added to pass message id in */
public static void setMessageID(String cid)
{
messageID = cid;
}
public static String getUniqueMessageIDValue(Session ssn) {
String suffix = null;
InternetAddress addr = InternetAddress.getLocalAddress(ssn);
if (addr != null)
suffix = addr.getAddress();
else {
suffix = "javamailuser#localhost"; // worst-case default
}
if(messageID == null)
{
messageID = "987654321";
}
StringBuffer s = new StringBuffer();
// Unique string is <messageID>.<id>.<currentTime>.FDDMail.<suffix>
s.append(messageID).append('.').append(getUniqueId()).append('.').
append(System.currentTimeMillis()).append('.').
append("FDDMail.").
append(suffix);
System.out.println("RETURNING THE new ID: " + s.toString()");
return s.toString();
}
private static synchronized int getUniqueId() {
return id++;
}
}
I call this MimeMessageClass from a mail wrapper called SimpleEmail. It is mostly a bunch of get/set functions. All of the meat is in the sendEmail method...
public String sendEmail()
{
String msgText1 = this.getBody();
// Create some properties and get the default Session
Properties props = System.getProperties();
props.put("mail.smtp.host", this.getSmtpClient());
props.put("mail.from", "");
Session session = Session.getDefaultInstance(props, null);
try
{
// Create a message
MyMimeMessage msg = new MyMimeMessage(session);
if (null != sender && sender.length() > 0)
{
msg.setSender(new InternetAddress(sender));
}
if((this.getReply_to() != null) && (this.getReply_to().length() > 0))
{
Address emailReplyTo[] = new Address[1];
emailReplyTo[0] = new InternetAddress(this.getReply_to());
msg.setReplyTo(emailReplyTo);
}
msg.setFrom(new InternetAddress(this.getFrom()));
if(this.to == null || this.to.size() <= 0)
{
return "Error: No To to send";
}
int toIndex = 0;
InternetAddress [] address = new InternetAddress [this.to.size()];
while(this.HasNextTo())
{
address[toIndex] = new InternetAddress(this.nextTo());
toIndex++;
}
msg.setRecipients(Message.RecipientType.TO, address);
if(this.subject == null)
{
this.subject = "<no subject>";
}
msg.setSubject(this.subject);
if(!useTextHeader)
{
//Create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setDataHandler(new DataHandler(new HTMLDataSource(msgText1)));
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
// Create the second message part
MimeBodyPart mbp2;
FileDataSource fds;
String filename;
if(this.attachments != null) {
Set attachmentPathAndNames = this.attachments.keySet();
Iterator attachmentIterator = attachmentPathAndNames.iterator();
while(attachmentIterator.hasNext()) {
String attachmentPathAndName = (String)attachmentIterator.next();
filename = (String)this.attachments.get(attachmentPathAndName);
if(filename == null) {
String[] dirs = attachmentPathAndName.split("\\/");
filename = dirs[dirs.length - 1];
}
mbp2 = new MimeBodyPart();
fds = new FileDataSource(attachmentPathAndName);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(filename);
//Create the Multipart and its parts to it
mp.addBodyPart(mbp2);
}
}
//add the Multipart to the message
msg.setContent(mp);
}
else
{
msg.setText(msgText1);
}
//set the Date: header
msg.setSentDate(new Date());
//set the MessageID Header
msg.setMessageID(this.messageID);
//send the message
try
{
Transport.send(msg);
}
catch(Exception e)
{
System.out.println("STOP WE THREW AN ERROR!!!!!!!!!!!!!!!");
}
}
catch (MessagingException mex)
{
mex.printStackTrace();
System.out.println("Error: SimpleEmail.SendEmail() = Caught MessagingException: " + mex.toString());
return "Error: SimpleEmail.SendEmail() = Caught MessagingException: " + mex.toString();
}
return this.SUCESS_MESSAGE;
}
So, when I call from a JSP I can see the two print statements from MyMimeMessage class
<%# page import="com.ifx.framework.SimpleEmail" %>
<%
String toAddr = request.getParameter("emailAddr");
String mid = request.getParameter("customID");
String SMTP_CLIENT = "myserver.mydomain.com";
String body = "Hi " + toAddr + "!<br>Today we are testing to see if the setting messageID to " + mid + " works!";
String sendResult = "No Email Sent";
if(toAddr != null)
{
SimpleEmail se = new SimpleEmail();
se.addTo(toAddr);
se.setSubject("Testing Headers");
se.setSmtpClient(SMTP_CLIENT);
se.setFrom("cms_zippylube#gointranet.com");
se.setBody(body);
se.setMessageID(mid);
sendResult = se.sendEmail();
}
%>
<!DOCTYPE html>
<html>
<head>
<title>
Test Page
</title>
<style>
label {
width: 200px;
display: inline-block;
margin-bottom: 5px;
}
</style>
</head>
<body>
<p style="background-color: #ADD8E6; border: solid 2px #000080;">
<%=sendResult%>
</p>
<form action="#" method="post">
<label for=emailAddr>Email Address:</label><input id="emailAddr" name="emailAddr" type="email"/> <br>
<label for=customValue>Custom Message ID:</label><input id="customID" name="customID" type="text"/> <br>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
In my logs I see:
Calling updateMessage()
RETURNING THE new ID: 8675309.0.1430500125923.FDDMail.javamailuser#localhost
When I check the resulting email, the Message-ID in the header matches what was set.
Here is where my problem is, when I run a standalone version it still sends out the email but doesn't call the updateMessageID method and does not print out the debugging statements.
import com.ifx.framework.SimpleEmail;
public class headerTest
{
public static void main(String args[])
{
String toAddr = args[0];
String mid = args[1];
String SMTP_CLIENT = "myserver.mydomain.com";
String body = "Hi " + toAddr + "!<br>Today we are testing to see if the header message id is retained";
String sendResult = "No Email Sent";
if(toAddr != null)
{
SimpleEmail se = new SimpleEmail();
se.addTo(toAddr);
se.setSubject("Testing Headers");
se.setSmtpClient(SMTP_CLIENT);
se.setFrom("dummy#test.com");
se.setBody(body);
se.setMessageID(mid);
sendResult = se.sendEmail();
}
System.out.println("Done!");
}
}
The only output that I get when I run this is:
Done!
whereas I am expecting
Calling updateMessage()
RETURNING THE new ID: 8675309.0.1430500125923.FDDMail.javamailuser#localhost
Done!
I've got my entire team (including sysadmin) stumped on this issue. Any and All suggestions would be greatly appreciated!
It sounds like you're testing with two different servers so I'm guessing that they're using different versions of JavaMail. What versions are they using? What does the JavaMail debug output show?

How can i chage name of image using java while uploading and save in folder? [duplicate]

This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 6 years ago.
<body>
<form method="post" action="DemoServlet" enctype="multipart/form-data" name="form1">
<input type="file" name="file" />
Image_Name:<input type="text" name="file"/>
<input type="submit" value="Go"/>
</form>
</body>
this is my index.jsp page.
This Servlet is DemoServlet when user click on submit button it will go here.while in jsp page suppose Image_Name given by user is IPL and actual name of image is funny.jpg then while saving the image it should store as IPL.png,here i'm able to upload image correctly with funny.jpg,but i need to save image as given name in text field of index.jsp page
public class DemoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Date date = new Date();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
if (isMultiPart) {
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator itr = upload.getItemIterator(request);
while (itr.hasNext()) {
FileItemStream item = itr.next();
if (item.isFormField()) {
String fieldname = item.getFieldName();
InputStream is = item.openStream();
byte[] b = new byte[is.available()];
is.read(b);
String value = new String(b);
response.getWriter().println(fieldname + ":" + value + "</br>");
} else {
String TempPath = getServletContext().getRealPath("");
String path = TempPath.substring(0, TempPath.indexOf("build"));
if (FileUpload.processFile(path, item)) {
out.println("File Uploaded on:" + date + "<br>");
response.getWriter().println("Image Upload Successfully");
} else {
response.getWriter().println("Failed.....Try again");
}
}
}
} catch (FileUploadException fue) {
fue.printStackTrace();
}
}
}
}
and this is java class
public class FileUpload {
public static boolean processFile(String path, FileItemStream item) {
try {
File f = new File(path + File.separator + "web/images");
if (!f.exists()) {
f.mkdir();
}
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
FileOutputStream fos = new FileOutputStream(savedFile);
InputStream is = item.openStream();
int x = 0;
byte[] b = new byte[1024];
while ((x = is.read(b)) != -1) {
fos.write(b, 0, x);
}
fos.flush();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
Could anybody guide me how to change this dynamically.Thanks in advance.
I don't know how Servlet's and the like work however i can give you a rundown of what you need to do.
In DemoServlet you need to take in the input of the Image_Name field and make that one of your parameters of FileUpload
public static boolean processFile(String path, FileItemStream item, String fileName){
//Method Code
}
Because currently your processFile method is taking the name of the file from your FileItemStream. You need to change it from that to your actual fileName
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
to
File savedFile = new File(f.getAbsolutePath() + File.separator + fileName + ".png");
You can change the name of image in your java class code.
public class FileUpload {
public static boolean processFile(String path, FileItemStream item , String name) {
try {
File f = new File(path + File.separator + "web/images");
if (!f.exists()) {
f.mkdir();
}
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName()); // instead of item.getName() you can give your name.
FileOutputStream fos = new FileOutputStream(savedFile);
InputStream is = item.openStream();
int x = 0;
byte[] b = new byte[1024];
while ((x = is.read(b)) != -1) {
fos.write(b, 0, x);
}
fos.flush();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
you will have to pass the file name in the method.
instead of item.getName() you can give your name.
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
System.out.println("In >>>>>>>>>>>>>>> :: "+fileItems);
while(i.hasNext()){
FileItem fi = (FileItem) i.next();
System.out.println("Val <<<<>>>>>>:: "+fi);
if(fi.isFormField()){
String fieldName = fi.getFieldName();
String val = fi.getString();
System.out.println(fieldName+" :: Val :: "+val);
}else{
String fileName = fi.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root+"/uploads");
if (!path.exists()) {
boolean status = path.mkdir();
}
File uploadFile = new File(path+"/"+fileName);
fi.write(uploadFile);
}
In the code above you can change the file name at any time and it will automatically save with this name.
//How does not work in this way?Please tell me another way.
import java.io.File;
public class RenameFileExample {
public static void main(String[] args)
{
File oldfile =new File("oldfile.txt");
File newfile =new File("newfile.txt");
File file = new File("oldfilename.png");
file.renameTo(new File("newfilename.png"));
System.out.println("Rename To:"+file.getName());
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
}

JavaScript alerts ???? for UTF-8 with spring?

I am doing a sample application for UTF-8 with Spring to support multi-language .
This is my JSP with Script ,
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%request.setCharacterEncoding("UTF-8");%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Test</h1>
<input type="text" id="hide" />
<input type="text" id="message"/>
<button id="button">test</button>
<div id="messageDisplayArea"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var contexPath = "<%=request.getContextPath() %>";
</script>
<script>
$('#button').on('click', sendMessage);
function sendMessage() {
var intxnId = $("#hide").val();
var message = $("#message").val();
alert("send : \n intxnId : " + intxnId + "\nmessage : " + message);
$.ajax({
type: "POST",
cache: false,
url: contexPath + "/test.html",
async: true,
data: "intxnId=" + intxnId + "&message=" + encodeURIComponent(message),
//dataType: "json",
dataType: "html",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
scriptCharset: "utf-8",
success: function(response) {
alert(response);
alert(response.message);
if (response !== null && response !== "" && response !== "null") {
var txt = '{"data":[' + response + ']}';
var json = eval("(" + txt + ")");
for (i = 0; i < json.data.length; i++) {
var data = json.data[i];
var name = data.name;
var message = data.message;
var time = data.time;
alert("Name : " + name + "\nMessage : " + message + "\ntime : " + time);
var createHTML = send(name, message, time);
$("#messageDisplayArea").append(createHTML);
}
;
}
},
error: function(e) {
alert('Error: ' + e);
},
});
function send(name , message , time){
var user = "<div id='user' class='fontStyle'>"+name+"</div>";
var msg = "<div id='msg' class='fontStyle'>"+message+"</div>";
var timeStamp = "<div id='time' class='fontStyle'>"+time+"</div>";
var row = "<div id='msgSet' >"+ user + msg + timeStamp +"</div>";
return row;
}
}
</script>
</body>
</html>
My Spring controller will be ,
#RequestMapping(value = "test.html", method=RequestMethod.POST , headers = "Accept=*",produces = "application/json; charset=utf-8")
public #ResponseBody String sendMessage(HttpSession session, #RequestParam String intxnId, #RequestParam String message, HttpServletRequest request, HttpServletResponse response) {
String contentType = "application/json; charset=utf-8";
response.setContentType(contentType);
try {
// request.setCharacterEncoding("utf-8");
request.setCharacterEncoding("application/json; charset=utf-8");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Send Message UTF-8 ----------------- " + message);
String json = null;
HashMap<String, String> result = new HashMap<String, String>();
result.put("name", "test");
result.put("message", message);
result.put("time", "time");
ObjectMapper map = new ObjectMapper();
if (!result.isEmpty()) {
try {
json = map.writeValueAsString(result);
System.out.println("Send Message :::::::: : " + json);
} catch (Exception e) {
e.printStackTrace();
}
}
return json;
}
My Controllers prints ,
Send Message UTF-8 ----------------- தமிழ் அரிச்சுவடி
Send Message :::::::: : {"message":"தமிழ் அரிச்சுவடி","time":"time","name":"test"}
In this my controller prints the local language . But in the JQuery success alert , I got message as ???? . I need to append the local language text in my JSP .
Hope our stack members will help me.
Following piece of code should solve your issue.
#RequestMapping(value="<your path>",produces = "application/json; charset=utf-8")
public #ResponseBody String sendMessage(#RequestParam String intxnId, #RequestParam String message) {
String json = null;
HashMap<String, String> result = new HashMap<String, String>();
result.put("name", "test");
result.put("message", message);
result.put("time", "time");
ObjectMapper map = new ObjectMapper();
if (!result.isEmpty()) {
try {
json = map.writeValueAsString(result);
System.out.println("Send Message :::::::: : " + json);
} catch (Exception e) {
e.printStackTrace();
}
}
return json;
}
This will produce UTF-8 ajax response.
Add mimeType:"application/json; charset=UTF-8" in jQuery.
I got the solution by changing the Controller as ,
#RequestMapping(value = "test.html", method=RequestMethod.POST , headers = "Accept=*",produces = "application/json; charset=utf-8")
public ResponseEntity<String> sendMessage(HttpSession session, #RequestParam String intxnId, #RequestParam String message, HttpServletRequest request, HttpServletResponse response) {
System.out.println("Send Message UTF-8 ----------------- " + message);
String json = null;
HashMap<String, String> result = new HashMap<String, String>();
result.put("name", "test");
result.put("message", message);
result.put("time", "time");
ObjectMapper map = new ObjectMapper();
if (!result.isEmpty()) {
try {
json = map.writeValueAsString(result);
System.out.println("Send Message :::::::: : " + json);
} catch (Exception e) {
e.printStackTrace();
}
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "application/json; charset=utf-8");
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}

Issue with multipart/form-data

I am not able to get values from both files and text input in a servlet when my form includes multipart/form-data. I am using the apache.commons.fileuploads for help with the uploads. Any suggestions. Also in the code below there are some things that I feel should be more efficient. Is there a better way to store these multiple files in a db.
public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
{
boolean promo = false;
Database db = new Database();
Homepage hp = db.getHomePageContents();
String part = ParamUtils.getStringParameter(request, "part", "");
if(part.equals("verbage"))
{
String txtcontent = (String)request.getParameter("txtcontent");
String promoheader = (String)request.getParameter("promoheader");
String promosubheader = (String)request.getParameter("promosubheader");
hp.setBodyText(txtcontent);
hp.setPromoHeader(promoheader);
hp.setPromoSubHeader(promosubheader);
System.err.println(txtcontent);
}
else
{
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart)
{
}
else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
//System.err.print(items);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if(item.getFieldName().equals("mainimg1"))
{
if(item.getName() !="") hp.setMainImg1(item.getName());
}
if(item.getFieldName().equals("mainimg2"))
{
if(item.getName() !="") hp.setMainImg2(item.getName());
}
if(item.getFieldName().equals("mainimg3"))
{
if(item.getName() !="") hp.setMainImg3(item.getName());
}
if(item.getFieldName().equals("promoimg1"))
{
promo = true;
if(item.getName() !="")
{
hp.setPromoImg1(item.getName());
try {
File savedFile = new File("/Library/resin-4.0.1/webapps/ROOT/images/promoImg1.jpg");
item.write(savedFile);
//System.err.print(items);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
if(item.getFieldName().equals("promoimg2"))
{
if(item.getName() !="")
{
hp.setPromoImg2(item.getName());
try {
File savedFile = new File("/Library/resin-4.0.1/webapps/ROOT/images/promoImg2.jpg");
item.write(savedFile);
//System.err.print(items);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
if(item.getFieldName().equals("promoimg3"))
{
if(item.getName() !="")
{
hp.setPromoImg3(item.getName());
try {
File savedFile = new File("/Library/resin-4.0.1/webapps/ROOT/images/promoImg3.jpg");
item.write(savedFile);
//System.err.print(items);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
System.err.println("FNAME =" + item.getFieldName() + " : " + item.getName());
if (item.isFormField()) {
}
else {
try {
if(!promo)
{
String itemName = item.getName();
File savedFile = new File("/Library/resin-4.0.1/webapps/ROOT/images/"+itemName);
item.write(savedFile);
}
//System.err.print(items);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
}
}
db.updateHomePageContent(hp);
When using multipart/form-data, the normal input field values are not available by request.getParameter() because the standard Servlet API prior to version 3.0 doesn't have builtin facilities to parse them. That's exactly why Apache Commons FileUpload exist. You need to check if FileItem#isFormField() returns true and then gather them from the FileItem.
Right now you're ignoring those values in the code. Admittedly, the FileItem is a misleading name, if it was me, I'd called it MultipartItem or just Part representing a part of a multipart/form-data body which contains both uploaded fields and normal parameters.
Here's a kickoff example how you should parse a multipart/form-data request properly:
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process normal fields here.
System.out.println("Field name: " + item.getFieldName());
System.out.println("Field value: " + item.getString());
} else {
// Process <input type="file"> here.
System.out.println("Field name: " + item.getFieldName());
System.out.println("Field value (file name): " + item.getName());
}
}
Note that you also overlooked a MSIE misbehaviour that it sends the full client side path along the file name. You would like to trim it off from the item.getName() as per the FileUpload FAQ:
String fileName = item.getName();
if (fileName != null) {
filename = FilenameUtils.getName(filename);
}
I have had similar problems in the past. The only way i could find round the problem was to put the fileupload into its own form.

Categories