I would like to get Coding To Upload Image(.jpg)/Photo to Server Machine using Struts1.x and
mySQL database I have the code for File Upload Instead.
Let me know what tweaking is required here. TC
Code for File Upload :----
public class FileUploadForm extends ActionForm{
private FormFile file;
public FormFile getFile() {
return file;
}
public void setFile(FormFile file) {
this.file = file;
}
#Override
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if( getFile().getFileSize()== 0){
errors.add("common.file.err",
new ActionMessage("error.common.file.required"));
return errors;
}
//only allow textfile to upload
if(!"text/plain".equals(getFile().getContentType())){
errors.add("common.file.err.ext",
new ActionMessage("error.common.file.textfile.only"));
return errors;
}
//file size cant larger than 10kb
System.out.println(getFile().getFileSize());
if(getFile().getFileSize() > 10240){ //10kb
errors.add("common.file.err.size",
new ActionMessage("error.common.file.size.limit", 10240));
return errors;
}
return errors;
}
}
Action Class:--
public class FileUploadAction extends Action{
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
FileUploadForm fileUploadForm = (FileUploadForm)form;
FormFile file = fileUploadForm.getFile();
//Get the servers upload directory real path name
String filePath =
getServlet().getServletContext().getRealPath("/") +"upload";
//create the upload folder if not exists
File folder = new File(filePath);
if(!folder.exists()){
folder.mkdir();
}
String fileName = file.getFileName();
if(!("").equals(fileName)){
System.out.println("Server path:" +filePath);
File newFile = new File(filePath, fileName);
if(!newFile.exists()){
FileOutputStream fos = new FileOutputStream(newFile);
fos.write(file.getFileData());
fos.flush();
fos.close();
}
request.setAttribute("uploadedFilePath",newFile.getAbsoluteFile());
request.setAttribute("uploadedFileName",newFile.getName());
}
return mapping.findForward("success");
}
}
Thanks in Advance!
Related
I have created assets folder inside resources. I want to display list of image names in the assets folder. By clicking image name, it should open the particular image. I can access the images separately but how to display all the images as file explorer.
You might use ResourcePatternResolver:
#Controller
#RequestMapping("/assets")
public class AssetController {
#Autowired
private ResourcePatternResolver resolver;
#GetMapping("")
#ResponseBody
public String resources() throws IOException {
final String root = resolver.getResource("classpath:/static/assets").getURI().toString();
final Resource[] resources = resolver
.getResources("classpath:/static/assets/**/*.png");
final List<String> fileNames = Stream.of(resources)
.filter(Resource::isFile)
.map(r -> {
try {
return r.getURI().toString().replace(root, "");
} catch (final IOException e) {
throw new IOError(e);
}
})
.collect(Collectors.toList());
final StringBuilder html = new StringBuilder();
html.append("<html>");
html.append("<ul>");
for (final String fileName : fileNames) {
html.append("<li>");
html.append("" + fileName + "");
html.append("</li>");
}
html.append("</ul>");
html.append("</html>");
return html.toString();
}
}
I want to upload file on remote server, currently i am only able to upload on local machine. below is my code
#PostMapping("/upload")
public UploadFileResponse uploadFile(#RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(fileName)
.toUriString();
return new UploadFileResponse(fileName, fileDownloadUri,file.getContentType(), file.getSize());
}
file.upload-dir=C:\\Test
Thanks in Advance!
EDIT:
1. Use case : You want to upload the file locally (i.e. where your application is running):
You create StorageService interface and an implementing class FileSystemStorageService:
#Service
public class FileSystemStorageService implements StorageService {
private final Path rootLocation;
#Autowired
public FileSystemStorageService(StorageProperties properties) {
this.rootLocation = Paths.get(properties.getLocation());
}
#Override
public void store(MultipartFile file) {
String filename = StringUtils.cleanPath(file.getOriginalFilename());
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + filename);
}
if (filename.contains("..")) {
// This is a security check
throw new StorageException(
"Cannot store file with relative path outside current directory "
+ filename);
}
try (InputStream inputStream = file.getInputStream()) {
Files.copy(inputStream, this.rootLocation.resolve(filename),
StandardCopyOption.REPLACE_EXISTING);
}
}
catch (IOException e) {
throw new StorageException("Failed to store file " + filename, e);
}
}
And the controller class:
#Controller
public class FileUploadController {
private final StorageService storageService;
#Autowired
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}
#PostMapping("/")
public String handleFileUpload(#RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
return "redirect:/";
}
You can find the whole sample under https://github.com/spring-guides/gs-uploading-files.
2. Use case : You want to upload the file to a remote server:
I recommend in this case to use SFTP.
You create a RemoteFileSystemStorageService implementing the StorageService (Already created in the first use case).
#Service
public class RemoteFileSystemStorageService implements StorageService {
#Autowired
private StorageProperties properties
final private ChannelSftp channelSftp;
#PostConstruct
public void setUpSsh(){
JSch jsch = new JSch();
Session jschSession = jsch.getSession(properties.getUsername(),
properties.getRemoteHost());
jschSession.setPassword(properties.getPassword());
jschSession.connect();
this.channelSftp = (ChannelSftp)jschSession.openChannel("sftp");
}
#Override
public void store(MultipartFile file) {
String filename = StringUtils.cleanPath(file.getOriginalFilename());
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + filename);
}
if (filename.contains("..")) {
// This is a security check
throw new StorageException(
"Cannot store file with relative path outside current directory "
+ filename);
}
try (InputStream inputStream = file.getInputStream()) {
this.channelSftp.connect();
this.channelSftp.put(inputStream, properties.getRemoteServerDirectory());
}
}
catch (IOException e) {
throw new StorageException("Failed to store file " + filename, e);
}
finally{
this.channelSftp.close();
}
}
In my app I m sending 3 parameters to server latitude,longitude and image.Earlier i was using volley for sending the parameter, but since i have a image also I had to use Multipart in my code.But i m getting an error while uploadind. In the notification bar the uploading starts but after some times it says error in uploading
Below is the code for MultiPart:
public void send() {
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, REGISTER_URL)
.setMethod("POST")
.addParameter("action", "location")
.addFileToUpload(imagePath, "data")//Adding file
//.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(5)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
Below is my volley code:
final String latitudee = String.valueOf(latitude);
final String longitudee =String.valueOf(longitude);
final String datae = imagePath;
//getting the actual path of the image
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MapsActivity.this,response,Toast.LENGTH_LONG).show();
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MapsActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("action","location");
params.put("latitude",latitudee);
params.put("longitude",longitudee);
send();
// params.put("data", datae);
//Uploading code
return params;}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Please help me where I'm going wrong
You can send your others parameters through Multipart request library too. just add "add parameter" to send more parameters.
I am newbee to Spring integration. i am trying to implement customer sftp filter to list the files in SFTP server. I am getting "The blank final field seen may not have been initialized" at the constructor.Can you please suggest me to get list of file names from sftp server.
I dont have any idea what went wrong in my code.
Thanks in Advance
java code
public class SFTPFileFilter extends SftpSimplePatternFileListFilter {
public SFTPFileFilter(String pattern) {
super(pattern);
// TODO Auto-generated constructor stub
}
final static Logger logger = LoggerFactory.getLogger(SFTPFileFilter.class);
private final Queue<File> seen;
private final Set<File> seenSet = new HashSet<File>();
private final Object monitor = new Object();
public static int fileCount = 0;
#Autowired
private SourcePollingChannelAdapter sftpInbondAdapter;
public List<File> filterFiles(File[] files)
{
List<File> accepted = new ArrayList<File>();
for (File file : files) {
System.out.println(file.getName());
accepted.add(file);
}
return accepted;
}
public boolean accept(File file) {
synchronized (this.monitor) {
if (this.seenSet.contains(file)) {
logger.info(file.getName()+" is already copied earlier");
return false;
}
if (this.seen != null) {
if (!this.seen.offer(file)) {
File removed = this.seen.poll();
this.seenSet.remove(removed);
this.seen.add(file);
}
}
this.seenSet.add(file);
return true;
}
}
}
private final Queue<File> seen;
You are not initializing that field in a constructor.
You can't extend it like that; simply override the method like this...
public List<File> filterFiles(File[] files) {
for (File file : files) {
System.out.println("received:" + file.getName());
}
List<File> filtered = super.filterFiles(files);
for (File file : flteredFiles) {
System.out.println("after filter:" + file.getName());
}
return filteredFiles;
}
I am new to spring. I have a controller with a RequestMapping for several GET parameters. They return a String .
But one method needs to return a file in the "/res/" folder. How do I do that?
#RequestMapping(method = RequestMethod.GET,value = "/getfile")
public #ResponseBody
String getReviewedFile(#RequestParam("fileName") String fileName)
{
return //the File Content or better the file itself
}
Thanks
Thanks to #JAR.JAR.beans. Here is the link: Downloading a file from spring controllers
#RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
#ResponseBody
public FileSystemResource getFile(#PathVariable("file_name") String fileName) {
return new FileSystemResource(myService.getFileFor(fileName));
}
May be this will help
#RequestMapping(method = RequestMethod.GET,value = "/getfile")
public #ResponseBody
void getReviewedFile(HttpServletRequest request, HttpServletResponse response, #RequestParam("fileName") String fileName)
{
//do other stuff
byte[] file = //get your file from the location and convert it to bytes
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("image/png"); //or whatever file type you want to send.
try {
response.getOutputStream().write(image);
} catch (IOException e) {
// Do something
}
}
Another way, though Jatin's answer is way cooler :
//Created inside the "scope" of #ComponentScan
#Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
#Value("${files.dir}")
private String filesDir;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/files/**")
.addResourceLocations("file:" + filesDir);
}
}
Lifted from:
http://www.baeldung.com/spring-mvc-static-resources
https://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources
This works like a charm for me:
#RequestMapping(value="/image/{imageId}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImage(#PathVariable String imageId) {
RandomAccessFile f = null;
try {
f = new RandomAccessFile(configs.getImagePath(imageId), "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);
f.close();
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(b, headers, HttpStatus.CREATED);
} catch (Exception e) {
return null;
}
}
If you are working on local Windows machine this could be useful for you:
#RequestMapping(value="/getImage", method = RequestMethod.GET)
#ResponseBody
public FileSystemResource getUserFile(HttpServletResponse response){
final File file = new File("D:\\image\\img1.jpg");
response.reset();
response.setContentType("image/jpeg");
return new FileSystemResource(file);
}
for testing your code you can use Postman "Use Send And Download not just send"
Another Approach to return byte:
#GetMapping("/getAppImg")
#ResponseBody
public byte[] getImage() throws IOException {
File serveFile = new File("image_path\\img.jpg");
return Files.readAllBytes(serveFile.toPath());
}