I'm very new to JAVA. I tried to save image through Java servlet and Ajax in netbeans. In netbeans I tried same coding with tomcat server is working fine.If I use Glashfish it's throwing error. Below is my coding.
Servlet:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Part img = request.getPart("img");
String id = (String) request.getParameter("ids");
out.println(saveImage(img, "E:\\Users\\XXXX\\Desktop\\wine_shop\\build\\web\\images\\wines"));
}
Save image method:
private String saveImage(Part img, String path) throws IOException {
File fileSaveDir = new File(path);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdirs();
}
System.out.println("Upload File Directory=" + fileSaveDir.getAbsolutePath());
String fileName = null;
fileName = extractFileName(img);
img.write(path+ fileName);
return "1";
}
My Error:
java.io.FileNotFoundException: E:\Users\xxxx\AppData\Roaming\NetBeans\8.2\config\GF_4.1.1\domain1\generated\jsp\wine_shop\E:\Users\xxxx\Desktop\wine_shop\build\web\images\winesth.jpg (The filename, directory name, or volume label syntax is incorrect)
Help to fix this..
Try This Code..
#WebServlet(name = "abc", urlPatterns = {"/upload"})
#MultipartConfig
public class abc extends HttpServlet {
private final static Logger LOGGER =
Logger.getLogger(abc.class.getCanonicalName());
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
final String path = "E:\\shopping\\web\\admin\\img";
final Part filePart = request.getPart("file");
final String fileName = getFileName(filePart);
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + path);
LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
new Object[]{fileName, path});
} catch (FileNotFoundException fne) {
writer.println("<br/> ERROR: " + fne.getMessage());
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
Related
I want to export odsfile like this
but I really got export is this(head line has extra word)
here is my code,Thanks for any suggestion
#RequestMapping(value = "/export", method = RequestMethod.POST)
public #ResponseBody void exportOds(Long questionId,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
VoteQuestion q = voteManager.getQuestion(questionId);
TableModel model = new DefaultTableModel(1000,1000);
File file = File.createTempFile("temp", ".ods");
model.setValueAt(q.getQuestion(), 0, 0);
int row = 2;
for (VoteOption opt : q.getOptions()) {
model.setValueAt(opt.getDescription(), row, 0);
model.setValueAt(opt.getVotes(), row++, 1);
}
SpreadSheet.createEmpty(model).saveAs(file);
String fileName = "投票結果";
String encodeFileName = FilenameEncoder.getInstance(request)
.encodeFileName(fileName + ".ods");
response.setHeader("Content-Disposition",
"attachment; filename=" + encodeFileName);
FileInputStream in = null;
OutputStream out = null;
try {
out = response.getOutputStream();
in = new FileInputStream(file);
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
file.deleteOnExit();
}
}
Solved by this code
#RequestMapping(value = "/export", method = RequestMethod.POST)
public #ResponseBody void exportOds(Long questionId,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
VoteQuestion q = voteManager.getQuestion(questionId);
String[] columName = new String[1000];
columName[0] = q.getQuestion();
for(int i = 1 ;i<1000;i++){
columName[i] = "";
}
TableModel model = new DefaultTableModel(columName,1000);
File file = File.createTempFile("temp", ".ods");
int row = 1;
for (VoteOption opt : q.getOptions()) {
model.setValueAt(opt.getDescription(), row, 0);
model.setValueAt(opt.getVotes(), row++, 1);
}
SpreadSheet.createEmpty(model).saveAs(file);
String fileName = "投票結果";
String encodeFileName = FilenameEncoder.getInstance(request)
.encodeFileName(fileName + ".ods");
response.setHeader("Content-Disposition",
"attachment; filename=" + encodeFileName);
FileInputStream in = null;
OutputStream out = null;
try {
out = response.getOutputStream();
in = new FileInputStream(file);
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
file.deleteOnExit();
}
}
I have a jsp page with a button, that link on a servlet and this create a pdf file an stream that as respons.
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
path = request.getServletContext().getRealPath("/");
String pdfFileName = "foo.pdf";
String contextPath = getServletContext().getRealPath(File.separator);
File pdfFile = new File(path + pdfFileName);
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);
response.setContentLength((int) pdfFile.length());
FileInputStream fileInputStream = new FileInputStream(pdfFile);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
}
the jquery is
$(document).ready(function() {
$(".getpdfbutton").click(function(){
var currentRow=$(this).closest("tr");
var col1=currentRow.find("td:eq(0)").html();
var data3=col1;
alert(data3);
$.get("PDFerzeugen",{Spass:data3}, function(data) {
/* window.location = data; */
alert(data);
});
});
I get the data respons as base64 , how can i download it as pdf file ?
i solved it over this script
function SaveToDisk(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName || 'unknown';
var evt = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
};
I have two node on production environment. I have placed pdf files at one server and want to read it from both server. when am calling 'file' method directly pdf get displayed in browser but when i call 'pdfFiles' nothing is displayed in browser.
public Resolution file(){
try {
final HttpServletRequest request = getContext().getRequest();
String fileName = (String) request.getParameter("file");
File file = new File("pdf file directory ex /root/pdffiles/" + fileName);
getContext().getResponse().setContentType("application/pdf");
getContext().getResponse().addHeader("Content-Disposition",
"inline; filename=" + fileName);
FileInputStream streamIn = new FileInputStream(file);
BufferedInputStream buf = new BufferedInputStream(streamIn);
int readBytes = 0;
ServletOutputStream stream = getContext().getResponse().getOutputStream();
// read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch (Exception exc) {
LOGGER.logError("reports", exc);
}
return null;
}
public Resolution pdfFile() {
final HttpServletRequest request = getContext().getRequest();
final HttpClient client = new HttpClient();
try {
String fileName = (String) request.getParameter("file");
final String url = "http://" + serverNameNode1 //having pdf files
+ "/test/sm.action?reports&file=" + fileName;
final PostMethod method = new PostMethod(url);
try {
client.executeMethod(method);
} finally {
method.releaseConnection();
}
} catch (final Exception e) {
LOGGER.logError("pdfReports", "error occured2 " + e.getMessage());
}
return null;
}
Included below part of code after 'client.executeMethod(method);' in 'pdfFile()' method and it works for me.
buf = new BufferedInputStream(method.getResponseBodyAsStream());
int readBytes = 0;
stream = getContext().getResponse().getOutputStream();
// write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
I have to delete and rename the files in doPost.but while executing some of the files are deleting some othes are not. When the same code i run in java the operation is succesfully carried out.here is the code i used for deleating files inside a directory.The same below code is i used in servlet.
public static void updateRootFile(String directorypath, String appID, String[] appName) throws IOException {
try {
FileInputStream fin = null;
File[] listOfFiles=fileLists(directorypath);
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
rootFiles = listOfFiles[i].getName();
if (rootFiles.endsWith(".properties") || rootFiles.endsWith(".PROPERTIES")) {
fin = new FileInputStream(directorypath + rootFiles);
properties.load(new InputStreamReader(fin, Charset.forName("UTF-8")));
String getAppName = properties.getProperty("root.label." + appID);
String propertyStr = "root.label." + appID;
saveFile(fin, getAppName, directorypath + rootFiles, propertyStr, appName[i]);
}
}
}
} catch (Exception e) {
System.out.println("expn-" + e);
}
}
public static void saveFile(FileInputStream fins, String oldAppName, String filePath, String propertyStr, String appName)
throws IOException {
String oldChar = propertyStr + "=" + oldAppName;
String newChar = propertyStr + "=" + appName;
String strLine;
File f1 = new File(filePath);
File f2 = new File("C:\\Equinox\\RootSipResource\\root\\root_created.properties");
BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(f1), "UTF-8"));
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(f2), "UTF-8");
while ((strLine = br.readLine()) != null) {
strLine = strLine.replace(oldChar, newChar);
out.write(strLine);
out.write("\r\n");
}
out.flush();
out.close();
br.close();
fins.close();
}
Servlet code:
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import root.sip.RootSipResourceApp;
public class SendRedirect extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
String strDirectorypath = (String) request.getParameter("txtfileBrowse");
request.setAttribute("directorypath", strDirectorypath);
String strappID = request.getParameter("txtAppID");
String[] appNames = {strEn, strAr, strBg, strCs, strDa, strDe, strEl, strEs, strFi, strFr, strHe, strHr, strHu, strIt,strLw, strJa, strKo, strNl, strNo, strPl, strPt, strRo, strRu, strSk, strSl, strSv, strTr, strZh, strZh_TW };
RootSipResourceApp.updateRootFile(strDirectorypath, strappID, appNames);
System.out.println("after................");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
}
It could be that your static methods are being accessed by multiple Servlet Threads at once.
You can make the saveFile() and updateRootFile() synchronized to prevent being accesed by multiple threads.
I am writing a small file upload utility thing as part of a larger project. Originally I was handling this from a servlet using the Apache commons File utility classes. Here is a snippet from a quick test client I wrote for the service:
public static void main(String[] args) {
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.getInInterceptors().add(new LoggingInInterceptor());
factory.getOutInterceptors().add(new LoggingOutInterceptor());
factory.setServiceClass(FileUploadService.class);
factory.setAddress("http://localhost:8080/FileUploadService/FileUploadService");
FileUploadService client = (FileUploadService) factory.create();
FileType file = new FileType();
file.setName("statemo_1256144312279");
file.setType("xls");
DataSource source = new FileDataSource(new File("c:/development/statemo_1256144312279.xls"));
file.setHandler(new DataHandler(source));
Boolean ret = client.uploadFile(file);
System.out.println (ret);
System.exit(0);
}
This works absolutely fine. Now the problem comes when I am trying to replace the Apache commons utilities. In the above code I am creating a DataSource from a File with an absolute path name. In my servlet, I can't get an absolute path name however and the file I am sending over the wire is empty.
Here is the servlet code:
#SuppressWarnings("unchecked")
protected void doPost (final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
// form should have enctype="multipart/form-data" as an attribute
if (!ServletFileUpload.isMultipartContent (request)) {
LOG.info("Invalid form attribute");
return;
}
//DataInputStream in = new DataInputStream(request.getInputStream());
final DiskFileItemFactory factory = new DiskFileItemFactory ();
factory.setSizeThreshold(FILE_THRESHOLD_SIZE);
final ServletFileUpload sfu = new ServletFileUpload (factory);
sfu.setSizeMax(MAX_FILE_SIZE);
final HttpSession session = request.getSession();
final List<FileItem> files = new ArrayList<FileItem>();
final List<String> filesToProcess = new ArrayList<String>();
try {
final List<FileItem> items = sfu.parseRequest(request);
for (final FileItem f : items) {
if (!f.isFormField())
files.add(f);
}
/*for (final FileItem f : files) {
final String absoluteFileName = UPLOAD_DESTINATION + FilenameUtils.getName(f.getName());
//f.write(new File (absoluteFileName));
filesToProcess.add(absoluteFileName);
}*/
FileItem f = files.get(0);
LOG.info("File: " + FilenameUtils.getName(f.getName()));
LOG.info("FileBaseName: " + FilenameUtils.getBaseName(f.getName()));
LOG.info("FileExtension: " + FilenameUtils.getExtension(f.getName()));
FileUploadServiceClient client = new FileUploadServiceClient();
DataSource source = new FileDataSource(new File(f.getName()));
FileType file = new FileType();
file.setHandler(new DataHandler(source));
file.setName(FilenameUtils.getBaseName(f.getName()));
file.setType(FilenameUtils.getExtension(f.getName()));
Boolean ret = client.uploadFile(file);
LOG.info("File uploaded - " + ret);
filesToProcess.add(UPLOAD_DESTINATION + FilenameUtils.getName(f.getName()));
session.setAttribute("filesToProcess", filesToProcess);
final RequestDispatcher dispatcher = request.getRequestDispatcher("Validate");
if (null != dispatcher) {
dispatcher.forward(request, response);
}
} catch (FileUploadException e) {
LOG.info("Exception " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
LOG.info("Exception " + e.getMessage());
e.printStackTrace();
}
}
I've been working on this for the better part of this morning and am not getting anywhere. Even if I get rid of the Apache commons file stuff completely and handle the parsing of the request myself, I still can't construct the DataSource appropriately.
Thanks!
This was rather simple actually, I just copied over the bytes from the InputStream to the DataSource:
FileItem f = files.get(0);
// there is a problem here where the file being created is empty, since we only have a
// partial path:
DataSource source = new FileDataSource(new File(f.getName()));
// because of the above problem, we are going to copy over the data ourselves:
byte[] sourceBytes = f.get();
OutputStream sourceOS = source.getOutputStream();
sourceOS.write(sourceBytes);
This is the code of commons-email ByteArrayDataSource
it sounds odd to try to replace apache commons - don't, unless you have a really good reason
you can get absolute paths in a servlet. You can call getServletContext().getRealPath("/") which will return the absolute path of your application, and then you can get files relative to it.
In our application there are objects that have properties InputStream and Name. We are using next class to construct DataSource with those properties.
public class InputStreamDataSource implements DataSource {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
private final String name;
public InputStreamDataSource(InputStream inputStream, String name) {
this.name = name;
try {
int nRead;
byte[] data = new byte[16384];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
inputStream.close();
buffer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public String getContentType() {
return new MimetypesFileTypeMap().getContentType(name);
}
#Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(buffer.toByteArray());
}
#Override
public String getName() {
return name;
}
#Override
public OutputStream getOutputStream() throws IOException {
throw new IOException("Read-only data");
}
}
Most of the solutions shown here require that the InpustStream be closed (read into memory). It is possible to wrap the InputStream in a DataSource object without closing the InputStream though:
private record PipedDataSource(InputStream in, String contentType, String encoding)
implements DataSource, EncodingAware {
public String getContentType() {
return contentType;
}
public InputStream getInputStream() {
return in;
}
public String getName() {
return "PipedDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("No OutputStream");
}
#Override
public String getEncoding() {
return encoding;
}
}
The example above also implements EncodingAware. This can prevent the InputStream from being closed by third part libraries (for example java.mail.internet.MimeUtility) when they get the data source encoding.