i wrote my code as below for download files:
String filename = request.getParameter("file").toString();
String filepath = request.getParameter("path").toString(); ;
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
FileInputStream fileInputStream=new FileInputStream(filepath + filename);
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
i was using this code in jsp page with scriplet tags ie <% %>
Now i tried it in servlet and now able to open the .xlsx file. the working code is as below:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String filename = request.getParameter("file").toString();
String filepath = request.getParameter("path").toString();
File f = new File (filepath + filename);
//set the content type(can be excel/word/powerpoint etc..)
String type = request.getParameter("type");
response.setContentType (type);
//set the header and also the Name by which user will be prompted to save
response.setHeader ("Content-Disposition", "attachment; filename=\""+filename+"\"");
//get the file name
String name = f.getName().substring(f.getName().lastIndexOf("/") + 1, f.getName().length());
//OPen an input stream to the file and post the file contents thru the
//servlet output stream to the client m/c
InputStream in = new FileInputStream(f);
try{
ServletOutputStream outs = response.getOutputStream();
int bytesRead;
byte[] buf = new byte[4 * 1024]; // 4K buffer
try {
while ((bytesRead = in.read(buf)) != -1){
outs.write(buf, 0, bytesRead);
}
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
outs.flush();
outs.close();
in.close();
}catch(Exception e){
e.printStackTrace();
}
}
Related
im working on a spring mvc project . i want to upload image and save it to resources/img/folder.
I tried below code but it does not save the image to the directory.
#Autowired
private HttpServletRequest request;
try {
// MultipartFile file = uploadItem.getFileData();
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (multipartFile.getSize() > 0) {
inputStream = multipartFile.getInputStream();
System.out.println("File Size:::" + multipartFile.getSize());
fileName = request.getSession().getServletContext().getRealPath("/resources/") + "/students/"
+ multipartFile.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
System.out.println("OriginalFilename:" + multipartFile.getOriginalFilename());
System.out.println("fileName----"+fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
Exception
11:00:39,436 INFO [stdout] (http--0.0.0.0-8080-5) File Size:::7346
11:00:39,436 ERROR [stderr] (http--0.0.0.0-8080-5) java.io.FileNotFoundException
: C:\jboss-as-7.1.1.Final\standalone\tmp\vfs\deployment65ea7dd580659db3\ObviousR
esponseWeb-1.2-SNAPSHOT.war-3a7509e73dad1cba\resources\students\zzzz.jpg (The sy
stem cannot find the path specified)
String saveDirectory=request.getSession().getServletContext().getRealPath("/")+"images\\";//to save to images folder
String fileName = multipartFile.getOriginalFilename();//getting file name
System.out.println("directory with file name: " + saveDirectory+fileName);
multipartFile.transferTo(new File(saveDirectory + fileName));
By using the following code a PDF file is getting opened, I simply write the file to the servlet's output stream, but, when i am trying to open that PDF file it showing an error : "Not a pdf or Corrupted"
My code:
public void displayPj() {
String url = ficheToDisplay.getUrl();
String outPutFile = ficheToDisplay.getNom();
HttpServletResponse resp = null;
resp = (HttpServletResponse) FacesContext.getCurrentInstance()
.getExternalContext().getResponse();
File file = new File(url);
resp.reset();
resp.setHeader("Content-Disposition", "attachment; filename=\""
+ outPutFile + "\"");
resp.setContentType("application/pdf;charset=UTF-8");
resp.setHeader("Content-Length", String.valueOf(file.length()));
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
ServletOutputStream outStream = resp.getOutputStream();
input = new BufferedInputStream(new FileInputStream(file),
DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(resp.getOutputStream(),
DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
outStream.close();
} catch (Exception e) {
System.err
.println("PROBLEM STREAMING DAILY REPORT PDF THROUGH RESPONSE!"
+ e);
e.printStackTrace();
FacesMessage fm = new FacesMessage("Could Not Retrieve PDF.");
FacesContext.getCurrentInstance().addMessage(
"dailyReportArchiveFailure", fm);
}
FacesContext.getCurrentInstance().responseComplete();
}
I have a problem regarding on uploading a file. When I upload the files myself(localhost) it actually works but when I let other people in the same network upload their file it gives me an error:
(The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at sources.UploadAIP.actions.uploadAction.processRequest(uploadAction.java:49)
Here is my actual code:
public class uploadAction extends AbstractAppAction
{
public boolean processRequest(HttpServlet servlet, HttpServletRequest request, HttpServletResponse response)
{
try{
Properties appProperties = getAppProperties();
String dbMap = appProperties.getProperty("dbMap");
DB db = getDBConnection(dbMap);
String myDirectory = "C:\\tmp";
String uploadedFile = request.getParameter("filename");
System.out.println("srcfile: " +myDirectory);
System.out.println("file: " +uploadedFile);
String errorMessage = "";
ServletContext sc = servlet.getServletContext();
String fileName = StringUtil.stringReplace(uploadedFile,"\\","\\");
int i = fileName.lastIndexOf("\\");
if (i > 0) {
fileName = fileName.substring(i+1);
}
File srcFile = new File(uploadedFile);
File targetDirectory = new File(myDirectory);
String dirname = StringUtil.stringReplace(targetDirectory.toString() ,"\\","\\");
System.out.println("directory name:" +dirname);
File destFile = new File(dirname+"\\"+fileName);
System.out.println(destFile);
System.out.println("here is the parent directory: " +targetDirectory);
if(!targetDirectory.exists()){
targetDirectory.mkdirs();
}
InputStream inStream;
OutputStream outStream;
try{
inStream = new FileInputStream(srcFile);
outStream = new FileOutputStream(destFile);
byte[] buffer = new byte[4096];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
outStream.close();
}catch(Exception e){
e.printStackTrace();
}
fileName = StringUtil.stringReplace(uploadedFile, "\\", "\\");
int u = fileName.lastIndexOf("\\");
if (u > 0)
{
fileName = fileName.substring(i + 1);
}
if (!dirname.endsWith("\\"))
{
dirname = dirname + "\\";
}
File f = new File(dirname);
String uploadDir = dirname;
System.out.println("uploadDirectory" +uploadDir);
} catch (Exception ex) {
request.setAttribute("message", ex.toString());
ex.printStackTrace();
}
return (true);
}
}
Your code assumes that the file being uploaded is present on the same local machine, which isnt true, since you are receiving uploads from a local network.
This is why it works on your local machine, but not across a network.
To upload a file, you need a multipart form and a servlet that correctly handles a multipart request.
This tutorial should help you:
http://www.avajava.com/tutorials/lessons/how-do-i-upload-a-file-to-a-servlet.html
I'm trying to upload a file to my Spring server running on Tomcat7. It's a simple POST request, the code is below:
#RequestMapping(method = RequestMethod.POST)
public void saveFile(HttpServletRequest request, #RequestParam("file_name") String fileName) {
Logger.getLogger(FileRestAction.class).info("saving file with name " + fileName);
try {
byte[] buf = readFromRequest(request);
String filePath = writeToFile(buf, fileName);
File_ file = new File_(filePath, request.getContentType());
Logger.getLogger(FileRestAction.class).info(request.getContentType() + " " + request.getContentLength());
fService.save(file);
} catch (IOException e) {
Logger.getLogger(FileRestAction.class).error("Failed to upload file. " +
"Exception is: " + e.getMessage());
}
}
private String writeToFile(byte[] buf, String fileName) throws IOException {
String fileBasePath = ConfigurationProvider.getConfig().getString(Const.FILE_SAVE_PATH);
File file = new File(fileBasePath + fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(buf);
fos.close();
Logger.getLogger(FileRestAction.class).info("filepath: " + file.getAbsolutePath());
return file.getAbsolutePath();
}
private byte[] readFromRequest(HttpServletRequest request) throws IOException {
InputStream is = request.getInputStream();
byte[] buf = new byte[request.getContentLength()];
is.read(buf);
is.close();
return buf;
}
Now the problem is that the file on the server is only "half-done", it's as if all the bytes aren't there. For example, if I send a 256x256 .png-file with a size of 54kB, the file written on the server is also 54kB and 256x256 in size, but the actual picture cuts off near the beginning (the rest is blank). No exceptions are thrown.
After a bit of testing I've found out that the cutoff is around 15-20Kb (images below that are fully uploaded).
Any ideas as to what might cause this?
EDIT: I changed the readFromRequest method according to what GreyBeardedGeek suggested. It's now as follows:
private byte[] readFromRequest(HttpServletRequest request) throws IOException {
InputStream is = request.getInputStream();
int fileLength = (int) request.getContentLength();
byte[] buf = new byte[fileLength];
int bytesRead = 0;
while (true) {
bytesRead += is.read(buf, bytesRead, fileLength - bytesRead);
Logger.getLogger(FileRestAction.class).info("reading file: " + bytesRead + " bytes read");
if (bytesRead == fileLength) break;
}
is.close();
return buf;
}
InputStream.read is not guaranteed to read the amount of data that you ask for.
The size that you ask for is the maximum number of bytes that it will read.
That's why the read() method returns the number of bytes actually read.
See http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#read(byte[])
So, the answer is to read multiple times, until read() returns -1
I am using the following code on the client side to upload to the server
public class UploaderExample{
private static final String Boundary = "--7d021a37605f0";
public void upload(URL url, List<File> files) throws Exception
{
HttpURLConnection theUrlConnection = (HttpURLConnection) url.openConnection();
theUrlConnection.setDoOutput(true);
theUrlConnection.setDoInput(true);
theUrlConnection.setUseCaches(false);
theUrlConnection.setChunkedStreamingMode(1024);
theUrlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary="
+ Boundary);
DataOutputStream httpOut = new DataOutputStream(theUrlConnection.getOutputStream());
for (int i = 0; i < files.size(); i++)
{
File f = files.get(i);
String str = "--" + Boundary + "\r\n"
+ "Content-Disposition: form-data;name=\"file" + i + "\"; filename=\"" + f.getName() + "\"\r\n"
+ "Content-Type: image/png\r\n"
+ "\r\n";
httpOut.write(str.getBytes());
FileInputStream uploadFileReader = new FileInputStream(f);
int numBytesToRead = 1024;
int availableBytesToRead;
while ((availableBytesToRead = uploadFileReader.available()) > 0)
{
byte[] bufferBytesRead;
bufferBytesRead = availableBytesToRead >= numBytesToRead ? new byte[numBytesToRead]
: new byte[availableBytesToRead];
uploadFileReader.read(bufferBytesRead);
httpOut.write(bufferBytesRead);
httpOut.flush();
}
httpOut.write(("--" + Boundary + "--\r\n").getBytes());
}
httpOut.write(("--" + Boundary + "--\r\n").getBytes());
httpOut.flush();
httpOut.close();
// read & parse the response
InputStream is = theUrlConnection.getInputStream();
StringBuilder response = new StringBuilder();
byte[] respBuffer = new byte[4096];
while (is.read(respBuffer) >= 0)
{
response.append(new String(respBuffer).trim());
}
is.close();
System.out.println(response.toString());
}
public static void main(String[] args) throws Exception
{
List<File> list = new ArrayList<File>();
list.add(new File("C:\\square.png"));
list.add(new File("C:\\narrow.png"));
UploaderExample uploader = new UploaderExample();
uploader.upload(new URL("http://systemout.com/upload.php"), list);
}
}
I have tried writing the servlet that receives the image file and saves it to a folder on the server....but have failed miserably...This is part of an academic project i need to submit as part of my degree....Please Help!!!
I want help ...can someone guide me on how the servlet will be written....
I tried the following:
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
InputStream input = null;
OutputStream output = null;
try {
input = request.getInputStream();
output = new FileOutputStream("C:\\temp\\file.png");
byte[] buffer = new byte[10240];
for (int length = 0; (length = input.read(buffer)) > 0 ; ) {
output.write(buffer, 0, length);
}
}
catch(Exception e){
out.println(e.getMessage());
}
finally {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
}
out.println("Success");
}
catch(Exception e){
out.println(e.getMessage());
}
finally {
out.close();
}
}
I went ahead and tried the fileupload from apache.org....and wrote the following servlet code:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println(1);
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
//processFormField(item);
} else {
//processUploadedFile(item);
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
//write to file
File uploadedFile = new File("C:\\temp\\image.png");
item.write(uploadedFile);
out.println("Sucess!");
}
}
} else {
out.println("Invalid Content!");
}
} catch (Exception e) {
out.println(e.getMessage());
} finally {
out.close();
}
}
However i am still confused on how to write the multipart code on the client side...the one i posted above is not working with my servlet implementation.....help please....some links where i can learn writing posting multipart form from java desktop app would be useful
So here's my recommendation: don't write this code yourself! Use http://commons.apache.org/fileupload/ instead. It will save you a lot of headaches, and you'll be up and running quite quickly. I'm pretty sure that problem is that the InputStream contains the multi-part boundaries, and is thus not a valid image.
Here's another observation: since you're not doing any transformations on the image, there's no need to read and write the image bytes using ImageIO. You're better off writing the bytes straight from the InputStream to the file.