Maven - Eclipse - Project I am trying to add an image to database , The image doesn't appear in my JSP page until i refresh the image - eclipse

This is the Controller page in which i have added my Image Upload Section .
When I add the product image to my database using a multi-part file and when i am listing it , the product thumbnail appears , once i refresh the resources - only then the image is displayed when i list it .
let me know what i should do .
#RequestMapping(value="/saveProd", method=RequestMethod.POST)
public ModelAndView gotoSave(#ModelAttribute("prod")Product prod,ModelMap m, Model a)
{
MultipartFile file = prod.getFile();
String fileName = "";
String image="";
if(!file.isEmpty())
{
try
{
System.out.println("inside try");
fileName = file.getOriginalFilename();
byte[] filesize=file.getBytes();
BufferedOutputStream bout=new BufferedOutputStream(new FileOutputStream(new File("\\C:\\Users\\GOOD\\workspace\\fionazcosmetics\\src\\main\\webapp\\resources\\images\\" + fileName)));
bout.write(filesize);
bout.close();
image="/resources/images/"+fileName;
//r.setAttribute("img" ,image);
m.addAttribute("img", image);
System.out.println("upload sucess.."+image);
}
catch (IOException e) {
System.out.println("upload failed..");
e.printStackTrace();
}
}
List<Supplier> x = supplierservice.getList();
a.addAttribute("sList",x);
List<Category> abc = categoryservice.getList();
a.addAttribute("cList",abc);
productDAOservice.insertRow(prod,image);
List ls=productDAOservice.getList();
return new ModelAndView("productadd","listProd",ls);
}

Related

Android 8 - FileProvider Uri opens a blank screen

I have the following code and it's only working on Android 7 and below. Android 8 only shows a blank file, I opened the pdf manually and works fine.
I have the following code and this is the repo:
private static final String SHARED_PROVIDER_AUTHORITY = BuildConfig.APPLICATION_ID + ".myfileprovider";
private static final String PDF_FOLDER = "pdf";
Bitmap bitmap = myCanvasView.getBitmap();
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#ffffff"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
document.finishPage(page);
// write the document content
File file = null;
try {
file = createFile();
document.writeTo(new FileOutputStream(file));
} catch (IOException e) {
e.printStackTrace();
showToast("Something wrong: " + e.toString());
}
// close the document
document.close();
Uri uri = getUriFrom(file);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(uri,"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
Where:
#NonNull
private Uri getUriFrom(File file){
if(Build.VERSION.SDK_INT >= 26) {
return FileProvider.getUriForFile(getApplicationContext(), SHARED_PROVIDER_AUTHORITY, file);
}
else{
return Uri.fromFile(file);
}
}
#NonNull
private File createFile() throws IOException {
if(Build.VERSION.SDK_INT >= 26){
final File sharedFolder = new File(getFilesDir(), PDF_FOLDER);
sharedFolder.mkdirs();
final File sharedFile = File.createTempFile(getFilename(), ".pdf", sharedFolder);
sharedFile.createNewFile();
return sharedFile;
}
else{
return new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ getFilename());
}
}
I found a solution for you. Just add flag Intent.FLAG_GRANT_READ_URI_PERMISSION to your intent:
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(uri,"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
I just tested it with your repo on Pixel 2 XL with Android 8.1 and got rid of this issue:
And got things working:
Hope this could help you! :)

How do i return a powerpoint (.pptx) file from REST response in springMVC

I am generating a powerpoint file(.pptx) and i would like to return back this file when a REST call happens. But now am able to get only .File type extension.
#RequestMapping(value = "/ImageManagerPpt/{accessionId}", method = RequestMethod.GET, produces = "application/ppt")
public ResponseEntity<InputStreamResource> createPptforAccessionId(#PathVariable("accessionId") String accessionId,HttpServletResponse response) throws IOException** {
System.out.println("Creating PPT for Patient Details with id " + accessionId);
File pptFile = imageManagerService.getPptForAccessionId(accessionId);
if (pptFile == null) {
System.out.println("Patient Id with id " + accessionId + " not found");
return new ResponseEntity<InputStreamResource>(HttpStatus.NOT_FOUND);
}
InputStream stream = null;
try {
stream = new FileInputStream(pptFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ClassPathResource classpathfile = new ClassPathResource("Titlelayout3.pptx");
InputStreamResource inputStreamResource = new InputStreamResource(stream);
return ResponseEntity.ok().contentLength(classpathfile.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(classpathfile.getInputStream()));
}
-Bharat
Have you tried, this?
InputStream stream = new InputStream(pptFile);
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
You will get file as you put into the InputStream.

Uploading file whose name is in unicode

I have some JavaScript code that upload file to server using ajax and form data and server side java code that accept it. I can upload English file name. But when I uploaded other Unicode file name, the file name I got in server side is unreadable. The following is code snippet.
JavaScript
var f = new FormData();
f.append("file", file);
xhr.send(f);
Java
public void upload(MultipartFormDataInput input) {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> inputParts = uploadForm.get("user_file[]");
IFileInfo file = null;
for (InputPart inputPart : inputParts) {
try {
MultivaluedMap<String, String> header = inputPart.getHeaders();
fileName = getFileName(header);
System.out.println("File name is " + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getFileName(MultivaluedMap<String, String> header) {
System.out.println("Headers is " + header.getFirst("Content-Disposition"));
String[] contentDisposition = header.getFirst("Content-Disposition")
.split(";");
for (String filename : contentDisposition) {
if ((filename.trim().startsWith("filename"))) {
String[] name = filename.split("=");
String finalFileName = name[1].trim().replaceAll("\"", "");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return finalFileName;
}
}
return "unknown";
}
When I upload "大家好.jpg" , I got server side log showing the following.
Headers is form-data; name="user_file[]"; filename="���������.jpg"
File name is ���������.jpg
I think browser encode file name before uploading it.But I don't know which encoding did it used or how to decode it back. Any help is much appreciated.

how to get file content from file using gwtupload

i am using GWTUpload to upload a file.
i am getting the server info, file name, content type etc.. in onFinishHandler, but there's no option to get the file content from server to client.
Note : am trying to upload XML File and EXCEL File
i am using GWT 2.4, GXT 3.0.1, GWTUpload 0.6.6
here's the sample code
Client Code - OnFinishHandler
u.addOnFinishUploadHandler(new OnFinishUploaderHandler() {
#Override
public void onFinish(IUploader uploader) {
if (uploader.getStatus() == Status.SUCCESS) {
System.err.println(uploader.getServerResponse());
UploadedInfo info = uploader.getServerInfo();
System.out.println("File name " + info.name);
System.out.println("File content-type " + info.ctype);
System.out.println("File size " + info.size);
System.out.println("Server message " + info.message);
}
}
});
Servlet Code
public class GWTFileUploadServlet extends UploadAction {
private static final long serialVersionUID = -6742854283091447922L;
String fileContent;
File uploadedFile;
#Override
public String executeAction(HttpServletRequest request,
List<FileItem> sessionFiles) throws UploadActionException {
String response = "";
int cont = 0;
for (FileItem item : sessionFiles) {
if (false == item.isFormField()) {
cont++;
try {
File file = File.createTempFile("upload-", ".bin");
item.write(file);
uploadedFile = file;
fileContent = item.getContentType();
response += "File saved as " + file.getAbsolutePath();
} catch (Exception e) {
throw new UploadActionException(e.getMessage());
}
}
}
removeSessionFileItems(request);
return response;
}
#Override
public void getUploadedFile(HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (fileContent != null && !fileContent.isEmpty()) {
response.setContentType(fileContent);
FileInputStream is = new FileInputStream(uploadedFile);
copyFromInputStreamToOutputStream(is, response.getOutputStream());
} else {
renderXmlResponse(request, response, XML_ERROR_ITEM_NOT_FOUND);
}
}
}
please help me....
You can read the file you have created in the filesystem when you called item.write(...), but it is better if you get an InputStream from the FileItem you received and write its content anywhere. For instance if the content is a String you can use a StringWritter to get it:
InputStream inputStream = item.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer);
String theContentString = writer.toString();
[EDITED]
To get the content of the file in client side, so you have to retrieve it from the server using any method:
As as a customized message in your gwtupload servlet if the content of the file is ascii: use return String of executeAction.
Do a RequestBuilder call to the servlet to get the file using the uploader url value.
Use any GWT ajax mechanism like RPC.
In modern browsers you can get the content of a file in client side without sending it to server side. Take a look to lib-gwt-file
In your code You can just use
byte[] file ;
file = item.get();
And You will get all the file content in an encoded format in the "file" variable .

GWT displaying image specified from servlet

I use a servlet to access a folder outside the web container to load some graphics to web application by using GWT. I use the following snippet in servlet to test the idea:
String s = null;
File inputFile = new File("C:\\Documents and Settings\\User\\My Documents\\My Pictures\\megan-fox.jpg");
FileInputStream fin = null;
try {
fin = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte c[] = new byte[(int) inputFile.length()];
try {
fin.read(c);
} catch (IOException e) {
e.printStackTrace();
}
try {
fin.close();
} catch (IOException e1) {
e1.printStackTrace();
}
String imgFolderPath = getServletContext().getRealPath("/")+"img";
File imgFolder = new File(imgFolderPath);
imgFolder.mkdir();
File newImage = new File("megan-fox.jpg");
FileOutputStream fout = null;
try {
fout = new FileOutputStream(newImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fout.write(c);
} catch (IOException e) {
e.printStackTrace();
}
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
boolean success = newImage.renameTo(new File(imgFolderPath, newImage.getName()));
The code in servlet reads the image file from the specified folder in hard disk, creates a new folder called 'img' in war folder and copies to it the jpg file. Then it returns to the client the path to the image (for now hardcoded as) '/img/megan-fox.jpg'.
The client then uses the Image class in GWT with the returned path-string to display the image, like in the following snippet:
public void onSuccess(String result) {
String myImage = result;
image = new Image(myImage);
RootPanel.get().add(image);
closeButton.setFocus(true);
}
I need to know if there is a way to achieve the same result without using the 'intermediate' step of creating a folder in the web container root (optional) and copying the file there in order to access it with Image GWT class and display it?
updated: The original servlet class.
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Get the absolute path of the image
ServletContext sc = getServletContext();
// i want to load the image in the specified folder (outside the web container)
String filename = sc.getRealPath("C:\\Documents and Settings\\User\\My Documents\\My Pictures\\megan-fox.jpg");
// Get the MIME type of the image
String mimeType = sc.getMimeType(filename);
if (mimeType == null) {
sc.log("Could not get MIME type of "+filename);
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Set content type
resp.setContentType(mimeType);
// Set content size
File file = new File(filename);
resp.setContentLength((int)file.length());
// Open the file and output streams
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.close();
}
// This is the method that is called from the client using GWT-RPC
public String greetServer(String input) throws IllegalArgumentException {
HttpServletRequest req = this.getThreadLocalRequest();
HttpServletResponse res = this.getThreadLocalResponse();
try {
doGet(req, res);
} catch (IOException e) {
e.printStackTrace();
}
// actually i dont know what that means but i thought i would have to returned something like the image's url?
return res.encodeURL("/img/image0.png");
}
}
I logically misused the method that was proposed to solve my problem. What is the correct way?
Sure, just have your servlet serve the image directly:
Set the Content-Type header to image/jpeg.
Write out image file contents to servlet response writer.
Here is an example.